简化选择器

问题描述 投票:0回答:2

我一直在努力简化一些查询选择器。我最好的办法是这样。

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

});

有没有一种方法可以在不扩展相同基础结构的选择器的情况下,包含我想要的索引列表?

javascript jquery jquery-selectors
2个回答
0
投票

没有JQuery 你可以用 活动代表团 并在事件处理程序中检查索引值。

侧面说明。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>

0
投票

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

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

$('.NextYearDays td[data-index]').filter(function() {
    return [1,2,3].includes(+$(this).data('index'))
}).on('change', function() {
    //event code here
});
© www.soinside.com 2019 - 2024. All rights reserved.