简体   繁体   English

在点击后在jQuery中添加复选框元素后无法正常工作

[英]On click not working after appending checkbox elements in jquery

The contact_container div holds contact children, within these children is a checkbox. contact_container div包含联系人子级,在这些子级中是一个复选框。 I use ajax to append these children to the container. 我使用ajax将这些子项附加到容器中。 Once I append the html and click a childs checkbox. 一旦我添加了html并单击childs复选框。 The .click does not recognize the newly added checkboxes, Only the children work on page load. .click无法识别新添加的复选框,只有子项才能加载页面。 Below are working samples of my HTML and Jquery. 以下是我的HTML和Jquery的工作示例。

Can you offer a solution so that the appended checkboxes are picked up when they are clicked? 您能提供一种解决方案,以便在单击附加的复选框时将其选中吗? Thanks 谢谢

Here is my HTML markup: 这是我的HTML标记:

   <div id="contact_container">
    <div class="contact">
        <div class="contact_checkbox">
             <div class="checkbox_container">
                 <div class="checkbox">
                     <input class="testing_checkbox" type="checkbox" name="contacts[]" value="bf6b0049059ec8998601f8fe20acb68ecafe2d44">
                </div>
             </div>
        </div>
        <div class="contact_info">
            <div class="contact_image">
                <img src="image.jpg" width="50" height="50" alt="Profile Picture">
            </div>
            <div class="contact_name"><span>Caroline Airey</span>
            </div>
       </div>
    </div>
</div>
<div id="x_message" class="inputdata" style="overflow: hidden; display: none;">
    <label>Message:</label>
    <span><textarea name="x_message" placeholder="Enter a message to send to your contact(s)"></textarea></span>
    <div class="clear"></div>
    <button class="form_button">Add Contact to Network</button>
</div>

Here is my Jquery: 这是我的Jquery:

$( ".checkbox" ).click(function() {
    var checked = $('.testing_checkbox:checked').length;
    $('#testing').val(checked);
    if (checked > 0){
        $('#x_message').show(1000);
    }
    else{
        $('#x_message').hide(1000);
    }
});

You will need the Parent reference to bind the element properly to jquery try this 您将需要Parent参考将元素正确绑定到jquery,尝试此操作

$(parentObj).on("click",".checkbox",function() {
var checked = $('.testing_checkbox:checked').length;
$('#testing').val(checked);
if (checked > 0){
    $('#x_message').show(1000);
}
else{
    $('#x_message').hide(1000);
}
});

The parentObj is the div or the html element you've appended the html code with ajax call parentObj是div或通过ajax调用附加了html代码的html元素

Use this jQuery method instead: 请改用以下jQuery方法:

$(".checkbox").on("click", function()
{
    // Your code here
});

This will grab clicks from elements that are dynamically added to your page after it initially loads :) 这将从最初加载后动态添加到页面的元素中获取点击:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM