您能否看一下这个演示并告诉我为什么我无法创建动态输入名称选择器?我想做的是根据 Bootstrap Tab 功能动态传递选择器的名称。
var checkname;
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
var target = $(e.target).attr("href") // activated tab
checkname = target.substring(1);
});
$("input:checkbox[name=" + checkname + "]").on('change', function() {
if ($(this).is(':checked')) {
alert('Checked');
} else {
alert('Un Checked');
}
});
@import 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="container">
<div class="col-md-3">
<ul id="myTab" class="nav nav-tabs">
<li class="active"><a href="#home" data-toggle="tab">Home</a>
</li>
<li class=""><a href="#profile" data-toggle="tab">Profile</a>
</li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="home">
<input type="checkbox" name="home" value="unit-in-group">Home
</div>
<div class="tab-pane fade" id="profile">
<input type="checkbox" name="profile" value="unit-in-group">Profile
</div>
</div>
</div>
</div>
最佳答案
扩展@tushar的评论:
By the time when the variable is used it is
undefined
, move the code of binding event at the end ofshow.bs.modal
问题是事件 show.bs.tab
被称为异步,因此当您尝试在 $("input:checkbox[name ="+检查名称+"]")
。您可以做什么,确保在触发 show.bs.modal
事件时首先绑定(bind) change
事件。
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// Activated tab
var target = $(e.target).attr("href");
// When we have the target we can bind the change event - not before!
bindChange(target.slice(1));
});
function bindChange(checkname) {
$("input:checkbox[name="+checkname+"]").on('change', function(){
if ($(this).is(':checked')) {
alert('Checked');
}
else {
alert('Un Checked');
}
});
}
关于javascript - 传递动态名称选择器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798456/