简体   繁体   English

如何干净地定义 $().on() 选择器

[英]How to cleanly define $().on() selectors

I am working with an existing jQuery (version 3.2.1) function:我正在使用现有的 jQuery(版本 3.2.1)函数:

$('#example').on('click', 'tbody td:not(:first-child)', 
   function (e) {
      // do stuff
  });

In this case, function(e) will only act if the TD is not the first column in the row.在这种情况下,只有当 TD 不是行中的第一列时,函数(e)才会起作用。

If I need to add some more not conditions (in what happens to be a table with at least 5 such columns), the function becomes something a little uglier.如果我需要添加更多的非条件(恰好是一个包含至少 5 个这样的列的表),该函数就会变得有点丑陋。

In testing it out, I know it works, but there's got to be a better way to do this.在测试它时,我知道它有效,但必须有更好的方法来做到这一点。

$('#example').on('click', 'tbody td:not(:first-child):not(:nth-
    child(2)):not(:nth-child(3))',  
function (e) {
   // do stuff
});

Is there a cleaner technique to indicate a set of not conditions in the selector?是否有更简洁的技术来指示选择器中的一组非条件? I was thinking that I could replace the selector string with a function, but I have not seen examples of that in use, even on the jQuery website .我想我可以用一个函数替换选择器字符串,但我还没有看到使用的例子,即使在jQuery 网站上

Are you looking for something like this ? 您是否在寻找像这样

$("#example")
  .not(":first-child")
  .not(":nth-child(2)")
  .not(":nth-child(3)")
  .on('click', 
    function (e) {
     // do stuff
   });

Disclaimer: I didn't check if this really works. 免责声明:我没有检查这是否真的有效。

@lilezek's answer is a good one. @lilezek的答案很好。 If you're looking to shorten your target to single lines, you can define the strings in a variable elsewhere, then pass the variable as the selector to your event handler. 如果您希望将目标缩短为单行,则可以在其他位置的变量中定义字符串,然后将该变量作为选择器传递给事件处理程序。

var selector_foo = 'tbody td:not(:first-child):not(:nth-
child(2)):not(:nth-child(3))'
...
$('#example').on('click', selector_foo, 
    function (e) {
        // do stuff
});

Using a class would be a much simpler solution. 使用类将是一个更简单的解决方案。 Just add the class you want to use to the cells you want to exclude and select as you normally would. 只需将要使用的类添加到要排除的单元格中,然后像往常一样选择即可。

tbody td:not(.exclude)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM