jquery在要检查的标记之前选中前一个复选框

jquery check previous check-box before a tag to be checked

本文关键字:复选框 一个 jquery 检查      更新时间:2023-09-26

我有一个类似的代码

<input type="checkbox" name="abc" value="A" class="chbx">
<a href="#" class="checkbox-selector">href1</a>
<input type="checkbox" name="abc" value="b" class="chbx">
<a href="#" class="checkbox-selector">href2</a>
<input type="checkbox" name="abc" value="c" class="chbx">
<a href="#" class="checkbox-selector">href3</a>

我想要的是,当我单击href1复选框时,应选中第一个复选框,当我点击href2时,应选择第二个复选框。

如何在jQuery中做到这一点?

您可以用不同的方式来实现这一点,并且完全不使用javascript

试试这个:

<label><input type="checkbox" value="hello" name="chkbox1" /> Here is the text</label>
<label><input type="checkbox" value="hello" name="chkbox2" /> Here is the text</label>
<label><input type="checkbox" value="hello" name="chkbox3" /> Here is the text</label>

您不需要jQuery。你可以使用普通的旧html。。。

<input type="checkbox" name="abc" id="chk1" value="A" class="chbx">
<label for="chk1" class="checkbox-selector">href1</label>
<input type="checkbox" name="abc" id="chk2" value="b" class="chbx">
<label for="chk2" class="checkbox-selector">href2</label>
<input type="checkbox" name="abc" id="chk3" value="c" class="chbx">
<label for="chk3" class="checkbox-selector">href3</label>

要添加对旧浏览器的支持(例如Fabricio建议的ie6),请使用scessor建议的jQuery方法:

$('.checkbox-selector').click(function() {
    $(this).prev().prop('checked', true);
});

请注意,如果您使用的浏览器不支持标签,则应同时实现并仅启用javscript方法。

如果使用标签,只要您给复选框一个ID并在标签中设置for属性,它就会自动为您选中该复选框。

<input type="checkbox" name="abc" value="A" class="chbx" id="c1">
<label for="c1" class="checkbox-selector">href1</label>
<input type="checkbox" name="abc" value="b" class="chbx" id="c2">
<label for="c2" class="checkbox-selector">href2</label>
<input type="checkbox" name="abc" value="c" class="chbx" id="c3">
<label for="c3" class="checkbox-selector">href3</label>

应用于前一个超链接的任何样式仍应应用于标签。

点击时检查和取消复选框的完整工作示例:

$('.checkbox-selector').click(function() {
    var chb = $(this).prev(); //caches selector
    chb.prop('checked', !chb.prop('checked')); //inverses checked state
});

Fiddle

但老实说,除非你真的需要与ie6和其他非html5浏览器等旧浏览器兼容,否则你应该使用<label>的方法。


如果name指的是链接的描述,只需使用$(this).text()即可获得单击的链接的文本
Fiddle

你必须这样做:

$('.checkbox-selector').click(function(){
    $(this).prev().attr('checked', true);
});