Jquery 委托事件仅在两个选择器之一上工作
Jquery Delegate event working on one of the two selectors only
$("body").on("change", "input[type='checkbox'],input[type=radio]", function(event){
$("input[type='checkbox']").on('change',function() {
var that = this;
if (!$(this).parent().hasClass("remember-label")){
$(this).parent().css("background-color", function() {
return that.checked ? "#C0E9F7" : "";
});
}
});
$("input[type=radio]").on('click',function() {
$(this).parents().eq(1).siblings().css("backgroundColor","");
$(this).parents().eq(1).css("backgroundColor","#C0E9F7");
});
});
虽然我想这应该有效,但它仅适用于单选按钮。由于每次内容动态更改时,我都必须放置两个选择器,因为有时单选按钮会添加到 DOM 中,有时还会添加复选框。
问题是输入的单击区域变得不可单击,除非您明确单击复选框或单选按钮而不是覆盖整个区域的标签。
这是HTML(它有轨道,但你可以理解结构)
<label for="choice_<%= choice.id %>">
<%= radio_button_tag("choice","#{choice.id}",false,class:"radio big-radio") %>
<% if choice.image? %>
<%= image_tag rewrite_url(choice.image_url(:resized)), class:"choice-image" %>
<% else %>
<%= choice.description %>
<% end %>
</label>
该代码适用于单选按钮,但同样适用于复选框。
为什么
你需要在事件处理程序中使用事件处理程序..简单地你可以像这样使用它
$(document).ready(function(){
$("body").on("change", "input[type='checkbox']",function() {
var that = this;
if (!$(this).parent().hasClass("remember-label")){
$(this).parent().css("background-color", function() {
return that.checked ? "#C0E9F7" : "";
});
}
});
$("body").on("click", "input[type=radio]" ,function() {
$(this).parents().eq(1).siblings().css("backgroundColor","");
$(this).parents().eq(1).css("backgroundColor","#C0E9F7");
});
});
注意:请确保包含 jquery
您应该只绑定一次:
$("body").on("change", "input[type='checkbox'],input[type=radio]", function(event){
// here you can check if this is check box or radio
if($(this).is(":checkbox")) {
// do this
}else{
// do for radios
}
});
相关文章:
- 两个日期时间选择器
- Javascript-如何使用bootstrap日期时间选择器自动计算两个时间输入之间的差异
- Javascript两个日期选择器冲突
- 如何从日期范围选择器中获取两个日期
- 只选择两个选择器中的一个
- (Angular+Bootstrap)如何阻止两个日期选择器被同一按钮打开
- 如何放置日期范围从周选择器用于两个文本输入
- jQuery 选择器,用于通过比较元素的两个数据属性来选择元素
- 如何在 d3 中选择前两个元素并对其应用过渡
- 检查是否同时选择了两个多选下拉列表
- 日期选择器多个日期在Google Apps Script中不起作用
- 引导验证程序&图像选取器-如果选择了两个可用的选择输入中的任何一个,如何验证表单
- 选择选择与两个下拉列表
- 猫鼬选择查询两个时间段
- 为什么比较“构造器”?两个Windows的属性不可靠
- 重定向到网页取决于选择在两个选择下拉框
- 选择两个按钮时选择多个按钮(必须选择位于两个按钮之间的按钮)
- 如果选择了两个选择值,则运行函数
- 日期选择器多个字段,其逻辑仅在少数字段中显示月份年份
- Javascript从数组中选择前两个