Tre*_*ski 2 javascript jquery jquery-ui reference 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'
});
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是html元素:
<input
name="appvAcadVp"
data-id="someid"
class="datepicker" size="10"
type="text"
placeholder="someholder"
>
Run Code Online (Sandbox Code Playgroud)
jQuery设置this
自己,通常指向当前元素.
否则,在JavaScript中......
var a = {
b: function() {
// `this` is `a`
}
}
a.b();
Run Code Online (Sandbox Code Playgroud)
除了,属性被分配给变量.观察...
var c = a.b;
c(); // the `this` will point to `window`
Run Code Online (Sandbox Code Playgroud)
var a = function() {
// `this` is `window`
}
a();
Run Code Online (Sandbox Code Playgroud)
var C = function() {
// `this` is `c`
}
var c = new C();
Run Code Online (Sandbox Code Playgroud)
请注意,如果您忘记实例化new
,JavaScript会将这些属性分配给全局对象(window
在浏览器中).
// In global scope `this` is `window`
var d = this;
Run Code Online (Sandbox Code Playgroud)
call()
或称为apply()
您还可以this
使用call()
和apply()
函数方法显式设置.
感谢'this'的解释,但我仍然不明白为什么引用不能在我的代码中工作
我很抱歉.
$(this).name
将不会像this
现在的jQuery对象一样工作,并且只有少数属性(没有一个属性name
).
使用$(this).attr('name')
或删除this
jQuery对象的包装,只需访问this.name
.
归档时间: |
|
查看次数: |
317 次 |
最近记录: |