给定:
var element = $('#element');
我想知道哪个更快:
element.click(function(){
element.dosomething()
)}
或者:
element.click(function(){
$(this).dosomething()
)}
或者重要吗?
最佳答案
使用元素
。
如果element
是匹配单个元素的jQuery集合,例如$(
someId)
,那么就使用它。
如果选择器要匹配多个元素,那么 element
实际上是 elements
,元素的集合,因此,在这种情况下,您使用 $(this)
在您的点击处理程序中以捕获实际点击的内容。
以下示例解释了差异:
1-单个元素上的处理程序
var table = $("#myTable");
table.click(function() {
// Same as $(this), except $(this) creates another
// wrapper on the same object (which isn't too expensive anyway)
table.doSomething();
});
2-多个元素上的处理程序
var rows = $("#myTable > tbody > tr");
rows.click(function() {
// Here we have to use $(this) to affect ONLY the clicked row
$(this).doSomething();
});
3-单个元素上的处理程序,但调用多个子元素
var table = $("#myTable");
// "on" and "live" call handler for only child elements matching selector
// (Even child elements that didn't exist when we added the handler,
as long as parent -table in this case- exists)
table.on("click", "tbody > tr", function() {
// Here we have to use $(this) to affect ONLY the clicked row
$(this).doSomething();
});
我发现它对现有的包装器来说是有保证的(而且工作量更少,但差别很小),这表明我在这种情况下期待一个元素,并且我只是在使用它。当我处理匹配元素集合中的元素时,请使用 $(this)
。
关于jQuery $(this) 与变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5160322/