![](/img/trans.png)
[英]jQuery - using the same function (ToggleNav/Dropdown) on multiple ID's
[英]JQuery : Assigning multiple id's to do the same function.
我认为一个相当简单的问题有一个简单的解决方案,但似乎无法想出正确的解决方法。
我有一组以3 x 3格式布局的按钮,我想改变点击时的属性,但是要独立。 我给了他们所有相同的课程,但是使用id来区分他们。
有没有办法在一行中为一组ID做同样的事情? 或者我必须冗余地写出每个按钮的呼叫。
我想简单地说,我可以写
$('.ready').click(function(){
if('.ready'.is('#7') || '.ready'.is('#8') || '.ready'.is('#9')){
execute 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>
你可以干脆做
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.
}
});
你不需要类.ready
选择器,因为id足够独特,可以作为选择器。
$('#7,#8,#9').click(function()
{
// do stuff
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.