JQuery:分配多个id's执行相同的功能

JQuery : Assigning multiple id's to do the same function.

本文关键字:执行 功能 分配 id JQuery      更新时间:2023-09-26

一个相当简单的问题,我觉得有一个简单的解决方案,但似乎想不出正确的解决方法。

我有一组3 x 3格式的按钮,我想在单击时更改它们的属性,但要独立更改。我给他们上了相同的课,但用id来区分他们。

有没有一种方法可以写,在一行中让一组ID做同样的事情?或者我必须多余地写出每个按钮的调用。

我想简单地说,我能写吗

 $('.ready').click(function(){
   if('.ready'.is('#7') || '.ready'.is('#8') || '.ready'.is('#9')){
      execute code.
   }
 });

如有任何帮助,我们将不胜感激!

您不需要类.ready选择器,因为id足够唯一,可以作为选择器作为目标。

 $('#7,#8,#9').click(function()
{
    // do stuff
});

您可以简单地执行

var pair1 = "#7, #8, #9";
var pair2 = "#2, #3, #4";
$('.ready').click(function(){
   if($(this).is(pair1)){
      execute code.
   }
   else if($(this).is(pair2)){
      execute some other code.
   }
});

使用.attr()函数获取id属性。

$('.ready').click(function() {
    var id = $(this).attr('id');
    if (id === '7' || id === '8' || id ==='9') {
        //execute code
    }
});

由于你的id是数字,你也可以只使用比较运算符。请参阅下面的工作示例,它将告诉您根据id单击了哪一行。

$(document).ready(function() {
  $('.ready').click(function() {
    var id = $(this).attr('id');
    if (id < 4) {
      $('#out').html('First row clicked');
    } else if (id < 7) {
      $('#out').html('Middle row clicked');
    } else {
      $('#out').html('Last row clicked');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="ready">1</button>
<button id="2" class="ready">2</button>
<button id="3" class="ready">3</button>
<br>
<button id="4" class="ready">4</button>
<button id="5" class="ready">5</button>
<button id="6" class="ready">6</button>
<br>
<button id="7" class="ready">7</button>
<button id="8" class="ready">8</button>
<button id="9" class="ready">9</button>
<span id="out"></span>