簡體   English   中英

jQuery查找復選框並選中/取消選中它

[英]jQuery find checkbox and check/uncheck it

我的循環創建的checkboxes

@foreach (L1 item in Model)
{
    <li><label class="checkbox"><input type="checkbox" id="@(item.Name)" 
         class="clink" value="@(item.Name)"/>@item.ForeName</label></li>
}

然后我使用jQuery來檢查它:

 $('#cworks').prop('checked', true);

以上不起作用。 這是使用firebug生成的html

<label class="checkbox"><input id="cworks" class="clink" value="cworks" type="checkbox">cworks</label>

如果復選框有“id”,那么您只需選擇它即可。

$('#Careworks_Map').prop('checked', true);

ID應該是唯一的。 因此,將該ID用作選擇器就足夠了(而且效率最高):

$('#Careworks_Map').prop('checked', true);

您必須使用類選擇器時使用id選擇器:

$('.checkbox input[id="Careworks_Map"]').prop('checked', true);

您還可以直接選擇要修改的復選框的ID:

$('#Careworks_Map').prop('checked', true);
$(":checkbox input[id='Careworks_Map']").attr("checked", true);

它不起作用,因為<label>聲明了一個class="checkbox"所以你需要搜索帶有句點的類. 然后定位內部復選框

$('#checkbox input[id="Careworks_Map"]').prop('checked', true); // wrong

$('.checkbox input[id="Careworks_Map"]').prop('checked', true); // right

在你的例子中你設置了一個class class="checkbox"然后在jquery調用中你使用了一個id #checkbox input所以為了使它工作,你應該這樣做:

$('.checkbox input[id="somestring"]').prop('checked', true);

然后,如果您的item.Name設置為類似var item.Name = my_prefix _somestring的前綴,則可以使用通配符。

 $('.checkbox input[id=*"my_prefix"]').prop('checked', true);

如果item.Name是唯一的(我假設),那么就這樣做:

$('#Careworks_Map').prop('checked', true);

編輯

根據您的更新,您應該這樣做:

$('#cworks').prop('checked', true);

http://jsfiddle.net/daguru/7FUBn/2/

使用id而不是class

$('#Careworks_Map')。prop('checked',true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM