[英]Getting a specific id using jquery
我有这样的代码:
<div class="answer_id" value="1" name="false">
<input id="AsnwerAnswer1" type="checkbox" value="1" name="true"></input>
Answer 1
</div>
我有4个答案,就像上面的代码一样,唯一改变的是我的div中的值和输入ID。
当我单击一个复选框时,选中的复选框将得到true值:
$("input:checkbox").click(function() {
var thisChecked = $(this)[0].checked;
$("input:checkbox").removeAttr('checked');
$("input:checkbox").attr('name', 'false');
$(this).attr('name', 'true');
$(this)[0].checked = thisChecked ? true : false;
});
当我点击按钮发送答案时:
$('#sendReponse').click(function(){
我想获取包含选定复选框(其值为true的div)的div的值。
我该添加些什么:
var iReponseId = $(this).closest('.answer_id').attr('value');
顺便说一句,如果您能帮助我理解单击功能的作用,那将是非常不错的。 根据我的说法,这会删除所有选中的属性,因此我只能选择一个复选框,这会将每个复选框的名称设置为false(对于期望被选中的复选框),但是我不明白:
$(this)[0].checked = thisChecked ? true : false;
编辑:
我这样做是为了得到我想要的东西:
$("input:checkbox").click(function() {
$("input:checkbox").not(this).prop('checked',false).removeAttr('class', 'chosen_answer');
$(this).attr('class', 'chosen_answer');
});
接着
$('#sendReponse').click(function(){
var iReponseId = $('.chosen_answer').closest('.answer_id').attr('value');
在您的代码$(this)[0].checked = thisChecked ? true : false;
$(this)[0].checked = thisChecked ? true : false;
在删除选中的属性后有助于回滚您之前选中的属性的状态,可以将其减少为this.checked = thisChecked
。
您可以按如下方式减少整个代码
// use change event always for chekbox
$("input:checkbox").change(function() {
// get all checkbox
$("input:checkbox")
.not(this) // ignore the clicked checkbox
.prop('checked',false) // uncheck the checkbox
.attr('name', 'false'); // set the attribute
$(this).attr('name', 'true'); // set name of clicked
});
为了获取包含输入的div,您需要使用answer_id
类而不是response_id
。
var iReponseId = $(this).closest('.answer_id').attr('value');
仅供参考:使用自定义属性时,请始终使用标准data-*
格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.