在下面的代码片段中,我使用 $(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"
>
最佳答案
jQuery 设置 this
本身,通常指向当前元素。
否则,在 JavaScript 中...
作为分配给属性的函数
var a = {
b: function() {
// `this` is `a`
}
}
a.b();
异常(exception),属性被分配给变量。观察...
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();
请注意,如果您忘记使用 new
进行实例化,JavaScript 会将这些属性分配给全局对象(浏览器中的window
)。
在全局范围内
// In global scope `this` is `window`
var d = this;
<小时/>
通过 call()
或 apply()
调用
您还可以使用 call()
和 apply()
函数方法显式设置 this
。
现在,解决你的问题...
Thanks for the explanation of 'this' but I still dont understand why the reference isn't working in my code
抱歉。
$(this).name
不起作用,因为 this
现在是一个 jQuery 对象,并且只有几个属性(其中没有一个是 name
)。
使用 $(this).attr('name')
或将 this
与 jQuery 对象包裹起来,然后访问 this.name
.
关于javascript - 'this' 是否引用调用此函数的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826467/