jQuery $(this) 与变量

标签 jquery performance

给定:

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/

相关文章:

jquery - 如何使用 Jquery 删除隐藏输入字段的 Name 属性?

c# - jQuery 属性不起作用

java - 当必须接受许多连接时,客户端/服务器类型应用程序中的Java套接字出现问题

c++ - 位设置和代码可读性

javascript, jQuery - 检查数组中是否存在值

javascript - 检测输入变化并同时写入其他输入

c# - 一次在同一张表中执行多个插入操作

c++ - 在 Intel CPU 上缓存对齐的内存分配

performance - 如何有效地从 Spark 中的每一列中找到不同的值

javascript - 在 JS 中撤消覆盖的粘贴