【问题标题】:Simplify Selectors简化选择器
【发布时间】:2020-08-29 09:30:33
【问题描述】:

我一直在努力简化一些查询选择器。我能做的就是这个。

$($(".NextYearDays td[data-index='1'], .NextYearDays td[data-index='2'] , .NextYearDays td[data-index='3']")).on("change", function ()
{

});

有没有办法在不扩展具有相同基本结构的选择器的情况下包含我想要的索引列表?

【问题讨论】:

  • 您可以使用$('.NextYearDays td').filter(function () { return +$(this).data('index') < 4 }) 之类的东西(但这实际上取决于 HTML 和您不想想要选择的元素)

标签: javascript jquery jquery-selectors


【解决方案1】:

欢迎来到Stackoverflow@Comelius Scheepers!我们希望您喜欢这里。

您可以按照@Chris G 的建议使用.filter() 方法,并使用[list-of-indices].includes( ... ) 之类的方法:

$('.NextYearDays td[data-index]').filter(function() {
    return [1,2,3].includes(+$(this).data('index'))
}).on('change', function() {
    //event code here
});

【讨论】:

    【解决方案2】:

    Without JQuery 你可以使用event delegation 并检查事件处理程序中的索引值。

    旁注:change 不是 <td> 的有效事件。

    const handle = evt => {
      const indx = evt.target.dataset.index;
      if (indx && [2,3,5].find( v => v === +indx )) {
        console.clear();
        console.log(`hi from ${evt.target.dataset.index}`);
      }
    };
    document.addEventListener("click", handle);
    td {cursor: pointer}
    <table>
      <tr>
        <td data-index="1"> 1 </td>
        <td data-index="2"> 2 </td>
        <td data-index="3"> 3 </td>
        <td data-index="4"> 4 </td>
        <td data-index="5"> 5 </td>
      </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 2010-11-15
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多