jQuery 插件可能存在范围问题?
我正在尝试制作一个 jquery 插件(只是为了好玩),但我似乎无法在某些部分做我想做的事情。
(function($){
var resetText = function(){ if (this.value == "") this.value = this.title; }
var clearText = function(){ if (this.value == this.title) this.value = ""; }
$.fn.placeHolder = function() {
return this.each(function(){
resetText(); // <-- this doesn't work
$(this).focus(clearText).blur(resetText);
});
};
})(jQuery);
基本上,我希望将 title 属性复制到 doc.ready 上和 field.blur 上的 value 属性(如果该值为空)
现在,它可以在Blur 上工作,但不能在 document.ready 上工作
我有一种感觉范围问题,但老实说我不知道如何解决它。
I'm trying to make a jquery plugin (just for fun) and I can't seem to a certain portion to do what I want.
(function($){
var resetText = function(){ if (this.value == "") this.value = this.title; }
var clearText = function(){ if (this.value == this.title) this.value = ""; }
$.fn.placeHolder = function() {
return this.each(function(){
resetText(); // <-- this doesn't work
$(this).focus(clearText).blur(resetText);
});
};
})(jQuery);
Basically, I want the title attribute to be copied over to the value attribute (if the value is empty) on doc.ready AND on field.blur
As it is now, it works onBlur but not on document.ready
I have a feeling it's a scope thing but honestly I don't know how to fix it.
See for yourself: http://jsfiddle.net/Usk8h/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到的是
this
问题,而不是范围问题。这样做:
.call()
方法允许您将resetText()
函数中this
的值设置为您传递的任何内容第一个论点。在本例中,您将在
.each()
中传递由this
表示的 DOM 元素。编辑:
您实际上可以将插件缩减为:
You have a
this
issue, not a scope issue.Do this instead:
The
.call()
method allows you to set the value ofthis
in theresetText()
function to whatever you pass as the first argument.In this case you're passing the DOM element represented by
this
in the.each()
.EDIT:
You could actually reduce your the plugin down to this:
这似乎确实是一个范围问题。这个怎么样?
http://jsfiddle.net/Usk8h/1/
It does appear to be a scope issue. How about this?
http://jsfiddle.net/Usk8h/1/