给定代码:
$(element, document).mousedown(function() {
$(this).attr('id'); // get id of the element
});
如何在不使用this
的情况下重写代码?
给定代码:
$(element, document).mousedown(function() {
$(this).attr('id'); // get id of the element
});
如何在不使用this
的情况下重写代码?
THIS 代表什么意思?
在这个上下文中,this
指的是你当前正在定义 mousedown
属性的元素。
我看不出为什么不能在这里使用它。您能详细说明一下您想做什么吗?
没有使用 this
关键字的版本:
var $element = $('#element');
$element.mousedown(function() {
var id = $element.attr('id');
// id is now 'element'
});
$(element, document).mousedown(function(e) {
$(e.target).attr('id'); // Get id of the element.
});
$("#button").mousedown(function(){
$("#button").attr("id");
})
把它留下来会更容易
"
。 - cwallenpoole在JavaScript中,this
代表函数的执行上下文。在这种情况下,您可以从jQuery设置this
为绑定元素受益。但是对于自编写的函数,通常会导致this
指向全局对象。
如果您进入新的函数作用域,通常需要保留this
,因为新函数具有新的this
。
例如:
$('div').each(function(index, item) {
var that = this;
$(this).mousedown(function() {
//this could be something different than before
//so we use the that reference
$(that).hide();
}
});
this
更有效率。其他所有方法都需要进行第二次元素查找,虽然不会非常昂贵,但仍然比使用作用域内的对象(this
)更加耗费资源。$(element, document).mousedown(function() {
$(element, document).attr('id');
});
现在,这可能还好,但如果您的元素实际上是一个返回多个值的选择器(例如类选择器),那么您将会遇到问题。因此,您可能需要考虑:
$(element, document).each( function( ind, elem ) {
elem.mousedown( function(){ elem.attr( 'id' ); } );
} );
$(element, document)
更改为$(selector, context)
,那么这非常相关。你正在询问该特殊情况内部的内容。 - naveen