我对这两个代码块之间的差异感到困惑:
$("#someButton").click(function() {
var button = this;
$(button).attr('disabled', 'disabled');
}
$("#someButton").click(function() {
var button = $(this);
$(button).attr('disabled', 'disabled');
}
请注意按钮变量存储内容的差异。将 $(this)
存储到按钮变量而不是仅存储 this
有何意义?最后,我仍然使用 $(button).jQueryMethod()
来操作它,而不是 button.jQueryMethod()
。
最佳答案
在您的示例中差异并不那么显着,因为您仅使用包装的 JQuery 对象一次。如果您需要多次使用 JQuery 对象,这个问题就变得更加重要。
$("#someButton").click(function() {
var button = this;
$(button).attr('disabled', 'disabled');
$(button).someJQueryMethod();
...
$(button).someOtherJQueryMethod();
}
在这种情况下,最好将对象包装一次并缓存结果。按照惯例,将结果缓存在以 $
符号开头的变量中,以指示它包含包装的 JQuery 对象。
$("#someButton").click(function() {
var $button = $(this);
$button.attr('disabled', 'disabled');
$button.someJQueryMethod();
...
$button.someOtherJQueryMethod();
}
这样,对 $()
的调用只会被调用一次。如果引用位于循环内,这一点就变得特别重要。
关于jquery - 对 jQuery 对象和 JavaScript 变量的不同使用场景感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8139372/