我将创建一个包含 10 个问题列表的页面。
每一行都是一个问题,每个问题有 4 个单选按钮(使用背景图像的水平无序列表)
当我单击第一个问题中的单选按钮时,我清除“checked”类的所有实例,然后将“checked”类添加到我单击的类中。但是,我在问题 1 中单击的按钮无法干扰问题 2 中的按钮。因此,我很难找到一种方法来使其成为每当我单击任何 li 项目时都会运行的全局函数。
这是我的代码:
编辑:将我的代码添加到 jsfiddle.net - http://jsfiddle.net/bnA4g/3/ --更新了链接
li {
list-style-type:none;
list-style:none;
display:inline-block;
white-space:nowrap;
}
.horiz {
background:url(blankRadio.png) no-repeat center center;
width:58px;
height:58px;
}
.checked {
background:url(checkedBtn.png) no-repeat center center;
width:58px;
height:58px;
}
$(function () {
var row1 = $('div#row1 ul > li');
var row2 = $('div#row2 ul > li');
$("ul#row1Btns li").click(function () {
$(row1).removeClass('checked');
$(this).addClass('checked');
console.log('checked');
});
$("ul#row2Btns li").click(function () {
$(row2).removeClass('checked');
$(this).addClass('checked');
console.log('checked');
});
});
最佳答案
你可以这样写:
$("div ul > li").click(function () {
$(this).siblings().removeClass('checked');
$(this).addClass('checked');
console.log('checked');
});
这应该符合您的预期。
关于jquery - 帮助优化和编写全局 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5490039/