我是这方面的新手。当我做编码的时候,我有一个问题。但我找不到解决问题的办法.
我想下面的代码,以更清楚地使用for-循环.我能为这个做些什么?
$('.special1').on("click",'.chkbutton1',function() {
$('.special1').toggleClass('effect-oscar effect-oscar-second');
});
$('.special2').on("click",'.chkbutton2',function() {
$('.special2').toggleClass('effect-oscar effect-oscar-second');
});
$('.special3').on("click",'.chkbutton3',function() {
$('.special3').toggleClass('effect-oscar effect-oscar-second');
});
<<omitted>>
$('.special11').on("click",'.chkbutton11',function() {
$('.special11').toggleClass('effect-oscar effect-oscar-second');
});
$('.special12').on("click",'.chkbutton12',function() {
$('.special12').toggleClass('effect-oscar effect-oscar-second');
});*/发布于 2016-08-10 05:35:30
您不需要使用for循环。您可以这样简单地使用:
$('[class^="chkbutton"]').on('click',function(){
$(this).parent() //not sure if .special.. is parent, select the correct element
.toggleClass('effect-oscar effect-oscar-second');
});我认为.parents('[class^="special"]')是合适的。
或者,您可以像这样使用delegateTarget:
$('[class^="special"]').on("click",'[class^="chkbutton"]',function(e) {
$(e.delegateTarget).toggleClass('effect-oscar effect-oscar-second');
});发布于 2016-08-10 05:36:07
这里不能使用for循环,但可以通过以下方式完成:
$('[class^=special]').on("click",'class^=chkbutton',function() {
var classList = $(this).attr("class"); //get all the classes associated with button; one of then will be starting with chkbutton
var classArray = classList.split(" ");
$.each( classArray, function( i, val ) {
if(val.indexOf("chkbutton") == 0)
{
var requiredClass = val;
var number = requiredClass.replace("chkbutton", ""); //grab the number
$('.special'+number).toggleClass('effect-oscar effect-oscar-second');
}
}
});注意:我无法测试上面的代码,但是我使用了有效的jquery,所以非常肯定它会按照预期工作。
https://stackoverflow.com/questions/38864893
复制相似问题