我正在使用下面的代码,它工作正常。我的问题是我需要点击实际的单选按钮来获取代码来完成它。
我还想添加一个点击处理程序,以便在用户点击 div 时也能触发事件
这是当前代码:
<script>
$(function(){
$("input[type=radio]").change(function() {
$("input[type='radio']", $(this).parent().parent()).each(function() {
$(this).parent()
.toggleClass("class_selected", this.checked)
.toggleClass("class_default", !this.checked);
});
});
});
</script>
更新:这是 HTML 代码:
<div class="def_app">
<span>Title Here</span>
<input type="radio" name="radio1" />
</div>
最佳答案
使用trigger
模拟事件已经发生,并调用与该事件关联的相应代码。
$(function(){
$("input[type=radio]").change(function() {
$("input[type='radio']", $(this).parent().parent()).each(function() {
$(this).parent()
.toggleClass("class_selected", this.checked)
.toggleClass("class_default", !this.checked);
});
});
//call trigger on the input
$("#yourdiv").click(function() {
$("input[type=radio]").trigger('change');
}
});
关于jQuery 给现有代码添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8712944/