‘this’是否指的是调用此函数的元素?
在下面的代码片段中,我使用$(this)
来引用调用函数的元素。 我知道这是不正确的,因为我打印出了值,它给了我’undefined’。 我如何参考输入元素?
$(function() { $( ".datepicker" ).datepicker({ onSelect: function (date, obj){ if(confirm('Is this correct?: '+ date )) { $.post('edit.php', { "row": $(this).data('id'), "date":date, "field":$(this).name, "ajax":'true' }); } } }); });
这是html元素:
我感谢任何帮助。 很抱歉这样的javascript noob ._。
jQuery设置this
本身,通常指向当前元素。
否则,在JavaScript中……
作为分配给一个人的function
var a = { b: function() { // `this` is `a` } } ab();
除了 ,属性被分配给变量。 观察…
var c = ab; c(); // the `this` will point to `window`
作为分配给变量的函数
var a = function() { // `this` is `window` } a();
作为构造函数
var C = function() { // `this` is `c` } var c = new C();
请注意,如果您忘记使用new
进行实例化,JavaScript会将这些属性分配给全局对象(浏览器中的window
)。
在全球范围内
// In global scope `this` is `window` var d = this;
用call()
或apply()
call()
您也可以使用call()
和apply()
函数方法显式设置this
。
现在,对你的问题……
感谢’this’的解释,但我仍然不明白为什么引用在我的代码中不起作用
我很抱歉。
$(this).name
将无法工作,因为this
现在是一个jQuery对象,只有几个属性(没有一个是name
)。
使用$(this).attr('name')
或者使用jQuery对象将其包装并只访问this.name
。
这就是onSelect函数中obj
参数的含义,因此你引用$(obj)
。 仅供参考, this
将引用相关的输入字段。
有关参考,请参阅: http : //jqueryui.com/demos/datepicker/ > Events> onSelect