我编码了以下内容:
var btnID = $link.attr('id');
var cityNumber = btnID.substring(4);
$('#cityLegend-1').html('City ' + cityNumber);
但是,只有当btnID以“btn-”开头时,我才需要这样做才能完成最后两行。有没有办法可以检查这种情况,然后如果id是“btn-1”或“btn-999”,那么最后两行呢?
答案 0 :(得分:6)
您可以使用.eq(-index)
,从集合中的最后一个元素向后传递索引计数。
<强> Live Demo 强>
$('[id^=cityLegend-]').eq(-1) for last
$('[id^=cityLegend-]').eq(-2) for second last
编辑,您可以使用split而不是substring来获取连字符后的数字。
var btnID = $link.attr('id');
var cityNumber = btnID.spilt('-')[1];
答案 1 :(得分:3)
/** .substring() does a length check internally **/
if (btnId.substring(0,3) == "btn") {
// do stuff
}
答案 2 :(得分:1)
这么多选择。这也有效:
var btnID = $(link).attr('id');
if(btnID.substr(0,4) == 'btn-'){
var cityNumber = btnID.substring(4);
$('#cityLegend-1').text('City ' + cityNumber);
}else{
$('#cityLegend-1').text('City ' + btnID);
}
答案 3 :(得分:0)
您可以使用.match()方法并使用正则表达式检查起始'id'是否以btn
开头。
if (btnID.match(/^btn/g)) {
//do stuff
}
答案 4 :(得分:0)
我不确定你的代码有多灵活,但我通常会采用类似的设置。我会做以下(可能或可能不适合你):
id
中搜索以某个字符串开头的元素,为什么不对您可能感兴趣的所有按钮使用特定的class
。这样,您就可以使用jQuery选择器,如$('.mySpecialBtn')
id
属性来包含id,而不是在data
的末尾附加一个整数,而不是data-my-button-id="1"
?所以要将两个部分组合在一起,你可能会有这样的事情:
HTML:
<button class="mySpecialBtn" data-my-button-id="1">Button 1</button>
<button class="mySpecialBtn" data-my-button-id="2">Button 2</button>
<button class="mySpecialBtn" data-my-button-id="3">Button 3</button>
JS:
$('mySpecialBtn').each(function() {
var btnId = $(this).data("my-button-id"));
// do something with btnId
});