动态生成复选框时,无法使用javascript访问复选框的键 [英] I can't access the keys of checkbox with javascript when I generate the checkbox dynamically

查看:109
本文介绍了动态生成复选框时,无法使用javascript访问复选框的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html.erb中创建了一个复选框,如下所示:

I created a checkbox in my html.erb as the following:

<%= check_box_tag(:fenix_fee_charged) %>
<%= label_tag(:fenix_fee_charged, "FENIX_FEE_CHARGED") %>
<%= check_box_tag(:fenix_fee_no_charged) %>
<%= label_tag(:fenix_fee_no_charged, "FENIX_FEE_NO_CHARGED") %>

我创建了JavaScript来设置一个或另一个:

I created the javascript to set one or another:

$('#fenix_fee_charged').click(function(){
    $('#fenix_fee_no_charged').removeAttr("checked");
});
$('#fenix_fee_no_charged').click(function(){
    $('#fenix_fee_charged').removeAttr("checked");
});

当我要检查的选项增加时,我决定动态创建该复选框:

When my options to check increased, I decided to create the checkbox dynamically:

<% Enums::FlightEnum::FENIX_FLIGHTS_NOTIFICATIONS.each do |notification, value| %>
  <%= check_box_tag notification, value %>
  <%= label_tag notification, notification.to_s.upcase, :class => "checkbox inline" %>
<% end %>

当我检查javascript函数时,此方法无效.我会很感激您能给我的任何帮助!

When I checked the javascript function, this did not work. I would appreciate any help that you can give me!

推荐答案

由于该复选框是动态添加的,因此您需要使用事件委托以注册事件处理程序

Since the checkbox are added dynamically, you need to use event delegation to register the event handler

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on('click', '#fenix_fee_charged', function(event) {
    $('#fenix_fee_no_charged').removeAttr("checked"); 
});

$(document).on('click', '#fenix_fee_no_charged', function(event) {
    $('#fenix_fee_charged').removeAttr("checked"); 
});

编辑

也尝试使用 .prop() 方法,例如:

Also try to use .prop() method like:

// Uncheck the checkbox
$('#fenix_fee_no_charged').prop("checked", false);

// Check the checkbox
$('#fenix_fee_no_charged').prop("checked", true);

这篇关于动态生成复选框时,无法使用javascript访问复选框的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆