我有一个包含图像或复选框的div集合。我的最终目标是让复选框上的onclick事件也检查所有以前的复选框。jQuery遍历元素得到所有匹配选择器的元素
这里是我的布局(动态创建这样编号的能够基于页面加载数据):
<div id="Main1">
<div id="Secondary1">
<div id="div1">
<img id="section1" src="image1" alt="" />
<span>Div 1 text</span>
</div>
<div id="div2">
<img id="section2" src="image2" alt="" />
<span>Div 2 text</span>
</div>
<div id="div3">
<input type="checkbox" id="section3">
Div 3 text
</input>
</div>
<div id="div4">
<input type="checkbox" id="section4">
Div 4 text
</input>
</div>
<div id="div5">
<input type="checkbox" id="section5">
Div 5 text
</input>
</div>
<div id="div6">
<input type="checkbox" id="section6">
Div 6 text
</input>
</div>
</div>
</div>
我希望能够检查section5并让它自动检查前面的复选框。
我一直在使用,这是产生零星结果的代码如下:
$('input[id^=section]').click(function() {
if($(this).attr('checked')) {
var slide = $(this).attr('id').replace('section', '');
$(this).replaceWith('<img src="images/ajax-loader.gif" id="loader" alt="" />'); //replace checkbox with loader animation
$.ajax({
type: 'POST',
url: 'URL to AJAX page',
data: '{ data for ajax call }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
$('#loader').parents('div[id^=Secondary]').children('div[id^=section]').each(function() {
if($(this).children('input[id^=section]').attr('id') != undefined) {
if($(this).children('input[id^=section]').attr('id').replace('section', '') < slide) {
$(this).children('input[id^=section]').replaceWith('<img src="images/checkmark.gif" alt="" />');
}
}
});
},
error: function() {
//handle errors
}
});
}
});
在我看来,我要对此低效,我曾试图.prev()
和.prevAll()
但没有成功。不过,我也可能错误地使用了它们。任何援助表示赞赏。
完美!感谢您的及时回应。还有1个问题,是否可以提取元素的ID? 我正在用图像替换复选框,并希望为图像提供与复选框相同的ID。使用你的代码片段,并用.replaceWith()代替.attr('checked','checked')来代替,但是我想要动态地取出被替换的元素的ID。这可能吗? – jon3laze 2010-09-03 23:21:47
@jon - 是的。如果您使用的是jQuery 1.4或更高版本,则可以将函数传递给'.replaceWith()',该函数将返回HTML字符串作为替换。在函数内部,你可以使用'this。id'来引用复选框的ID。我会用一个例子来更新。 – user113716 2010-09-03 23:31:06
太棒了!再次感谢你,这帮了一大笔钱。 – jon3laze 2010-09-04 00:25:57