我在页面中有很多复选框和相关的文本框。默认情况下隐藏文本框,仅在选中相关复选框时显示。我应该如何为此编写一个通用函数,而不是每个复选框的函数。
something..like ..:
$("input[type=checkbox]").click( function() {
var x = $(this).attr("name");
$("[id=x]").toggle(this.checked);
});
'名称'该复选框将是其文本框的ID。
答案 0 :(得分:3)
你需要:
1)在你的小提琴中加入jQuery
2)使用change()
事件代替click()
3)使用x
+
变量
$("input[type=checkbox]").change( function() {
var x = $(this).attr("name");
$("#" + x).toggle(this.checked);
});
<强> Updated Fiddle 强>
答案 1 :(得分:2)
在此上下文中您不需要attribute selector
,因为您要定位ID,只需使用下面的Id选择器,
尝试,
$("#" + $(this).attr("name")).toggle(this.checked);
完整代码,
$("input[type=checkbox]").change( function() {
$("#" + $(this).attr("name")).toggle(this.checked);
});
答案 2 :(得分:2)
在你的小提琴中加入jQuery,并且:
$("input[type=checkbox]").click( function() {
var x = $(this).attr("name");
$("[id="+x+"]").toggle(this.checked);
});
答案 3 :(得分:1)
由于您的文本框紧跟复选框,因此您可以执行以下操作:
$('input[type=checkbox]').click(function() {
$(this).next().css('display', this.checked ? 'block': 'none');
});
答案 4 :(得分:1)
如果您的问题是,如何在不将函数调用绑定到每个复选框的情况下完成此显示/隐藏功能?然后解决方法是将函数绑定到包装表的div或表本身。然后当onClick on div fires时,遍历子dom元素,如果选中了复选框,则根据需要显示或隐藏文本。如下所示:
$("wrapper_div_id").click(function() {
var checkboxes = $(this).find(":checkbox")
for (var i = 0; i < checkboxes.length; i++) {
// insert code here to show/hide. Sorry, I got lazy to finish writing the rest of this
// but you get the idea.
}
})
答案 5 :(得分:0)
检查一下
$('input[type=checkbox]').click(function(){
if( $(this).is(":checked") ){
$(this).next().show()
}else{
}
});