Javascript 是否';这';是否引用调用此函数的元素?
在下面的代码段中,我使用Javascript 是否';这';是否引用调用此函数的元素?,javascript,jquery,jquery-ui,reference,this,Javascript,Jquery,Jquery Ui,Reference,This,在下面的代码段中,我使用$(this)引用调用函数的元素。我知道这是不正确的,因为我打印了值,它给了我“未定义”。如何引用输入元素 $(function() { $( ".datepicker" ).datepicker({ onSelect: function (date, obj){ if(confirm('Is this correct?: '+ date )) { $.post('edit.p
$(this)
引用调用函数的元素。我知道这是不正确的,因为我打印了值,它给了我“未定义”。如何引用输入元素
$(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元素:
<input
name="appvAcadVp"
data-id="someid"
class="datepicker" size="10"
type="text"
placeholder="someholder"
>
这就是onSelect函数中的
obj
参数的作用,因此您可以引用$(obj)
。仅供参考,此
将引用相关的输入字段
有关参考信息,请参见:>Events>onSelectjQuery设置
此
本身,通常指向当前元素
否则,在JavaScript中
作为分配给属性的函数
除非将属性指定给变量。观察
var c = a.b;
c(); // the `this` will point to `window`
作为分配给变量的函数
作为构造器 请注意,如果忘记使用
new
实例化,JavaScript将把这些属性分配给全局对象(浏览器中的窗口
)
在全球范围内
使用
call()
或apply()调用
您还可以使用call()
和apply()
函数方法显式设置this
现在,关于你的问题。。。
感谢您对“this”的解释,但我仍然不明白为什么我的代码中没有引用
我道歉
$(this).name
将不起作用,因为this
现在是一个jQuery对象,并且只有几个属性(其中没有一个是name
)
使用jQuery对象使用$(this.attr('name')
,或者直接使用jQuery对象包装this
,只需访问this.name我试过了,当我打印它时,它给了我“undefined”(未定义)obj
是日期选择器的实例,虽然此
是触发事件的元素。感谢您对“此”的解释,但我仍然不明白为什么引用在我的代码中不起作用
var c = a.b;
c(); // the `this` will point to `window`
var a = function() {
// `this` is `window`
}
a();
var C = function() {
// `this` is `c`
}
var c = new C();
// In global scope `this` is `window`
var d = this;