【发布时间】:2012-04-05 22:04:07
【问题描述】:
鉴于此 HTML:
<div id="foo">
<input type=button class="foo abtn_1">
<input type=button class="joe bbtn_2">
<input type=button class="doe cbtn_2">
<input type=button class="cool dbtn_1">
</div>
当我单击一个按钮时,我需要获取包含下划线的类(仅)并将其编号从 2 更改为 1。
目前我在每个班级都使用这个:
$('.abtn_1').live('click', function () {
$(this).switchClass('abtn_1','abtn_2');
});
$('.abtn_2').live('click', function () {
$(this).switchClass('abtn_2','abtn_1');
});
$('.bbtn_1').live('click', function () {
$(this).switchClass('bbtn_1','bbtn_2');
});
$('.bbtn_2').live('click', function () {
$(this).switchClass('bbtn_2','bbtn_1');
});
// etc
因此,我没有多次这样做,而是想通过获取下划线类并相应地更改它的数字来将整个事情变成一两行。
我想它会是这样的:
var a = // $(this).attr('class') without number and underscore
var b = // This class number only
var c = $(this).attr('class'); // If I wanted to call it from
// its parent $('#foo input').
if a contains number 1 {
$(this).switchClass(c, a + '_1')
} else {
$(this).switchClass(c, a + '_2')
};
【问题讨论】:
-
您可以使用正则表达式来获取数字,或者只包含最后一个字符的子字符串。顺便说一句: .live() 已弃用。我不知道您使用的是哪个 jQuery 版本,但从 1.7 开始,您应该使用 .on() 而不是 .live()
-
我的客户想要使用不存在的 jQuery 1.6。虽然那不是我的问题。至于正则表达式,我知道我需要做什么。我只是想不通,否则我会问。谢谢
标签: jquery class replace switch-statement