简体   繁体   English

无法与通过jquery追加添加的dom对象进行交互

[英]Cannot interact with dom objects added with jquery append

I've added tr and td tags to a table using append but I jQuery doesn't seem to know the dom objects are there (I thought that's what append/prepend did?). 我已经使用append将tr和td标签添加到表中,但我的jQuery似乎并不知道dom对象(我认为那是append / prepend所做的事情?)。 When I run the script the table row is added and the user can see it but jQuery isn't catching the click handler on the hyperlink or anything else. 当我运行脚本时,将添加表行,用户可以看到它,但是jQuery不能捕获超链接或其他任何内容上的单击处理程序。 I've done the same thing on a different page that works great. 我在不同的页面上做了同样的事情,效果很好。 I've included that as well. 我也包括了。 If someone could please tell me where my train of thought got derailed, I'd be much obliged. 如果有人可以告诉我我的思路出轨了,我将非常有义务。 Also if I'm going about this the wrong way please let me know so I can improve. 另外,如果我要以错误的方式进行操作,请告诉我,以便我可以改进。

broken code: 损坏的代码:

    $("#addAdmin").click(function(){
                $("#chosenAdmins").append('<tr id = "admin' + $("#admins").val() + '"><td align="left">' + $("#admins option:selected").text() + ' </td><td align="right"><a href="#" class = "removeAdmin" id = "ra" style = "font-size: 10px;">Remove</a></td><tr>');
    });
    $(".removeAdmin").click(function(e){
        e.preventDefault();
        alert('clicked');
        alert(this.attr(id));
    });
    <select id = "admins">
        <option value = "1">bob smith</option>
    </select> 
    <input type = "button" id = "addAdmin"/>
    <table id = "chosenAdmins" align="center" width="0%"> </table>

The similar code that works on a different page is: 在不同页面上工作的类似代码是:

    $(document).ready(function() {
        var leftData = '<div id = "l1">left Stuff</div>';
        var leftData = leftData + '<div id = "l2">left Stuff</div>';
        var rightData = '<div id = "r1">right Stuff</div>';
        var rightData = rightData + '<div id = "r2">right Stuff</div>';
        $("#selector").prepend("<div id = 'leftSelect' style = 'float:left'>"+leftData+"</div><div id = 'rightSelect' style = 'float:left'>"+rightData+"</div>");
        $("#l1").click(function(){
            $(this).hide("fast", function(){
                $(this).prependTo('#rightSelect');
                $(this).show("fast");
            });
        });
     });

<div id = "selector"> </div>

You are defining your event handler ( $('.removeAdmin').click() ) before there are any .removeAdmin elements on the page. 您要在页面上没有任何.removeAdmin元素之前定义事件处理程序( $('.removeAdmin').click() )。

What you need to do is delegate your events. 您需要做的就是委派活动。 Assuming you're using the latest jQuery: 假设您使用的是最新的jQuery:

$("#chosenAdmins").on('click','.removeAdmin',function(e){
    e.preventDefault();
    alert('clicked');
    alert(this.attr(id));
});

This way, the event handler is attached to an element that exists, namely, the chosenAdmins table. 这样,事件处理程序将附加到存在的元素,即chosenAdmins表。

NOTE It is not recommended to use .live , as this attaches events to the document, and other code may inadvertantly remove these events. 注意不建议使用.live ,因为这会将事件附加到文档中,并且其他代码可能会无意中删除这些事件。 If you are using jQuery < 1.7, use delegate : 如果您使用的是jQuery <1.7以下版本,请使用delegate

$("#chosenAdmins").delegate('.removeAdmin','click',function(e){
    e.preventDefault();
    alert('clicked');
    alert(this.attr(id));
});

.removeAdmin doesn't exist yet when the click handler is added. 添加点击处理程序时, .removeAdmin尚不存在。 Try this: 尝试这个:

$("#addAdmin").click(function(){
        var tr = $("#chosenAdmins").append('<tr id = "admin' + $("#admins").val() + '"><td align="left">' + $("#admins option:selected").text() + ' </td><td align="right"><a href="#" class = "removeAdmin" id = "ra" style = "font-size: 10px;">Remove</a></td><tr>');
        $(".removeAdmin", tr).click(function(e){
            e.preventDefault();
            alert('clicked');
            alert(this.attr(id));
        });

    });
    <select id = "admins">
        <option value = "1">bob smith</option>
    </select> 
    <input type = "button" id = "addAdmin"/>
    <table id = "chosenAdmins" align="center" width="0%"> </table>

Also, be careful of using id="ra" in your row. 另外,请注意在行中使用id="ra" Since #addAdmin could potentially be clicked more than once, you could end up with multiple elements with the same ID which will make your junk FREAK OUT! 由于#addAdmin可能会被多次单击,因此您最终可能会获得多个具有相同ID的元素,这将使您的垃圾#addAdmin

For dynamically created elements, you need the live function: 对于动态创建的元素,您需要live函数:

$("#elem").live("click", function() {
    // Code here
});

Works with, click, hover and all types of functions. 可使用,单击,悬停和所有类型的功能。

http://api.jquery.com/live/ http://api.jquery.com/live/

You've got a typo in the .append (forgot to add forward slash), fix the broken HTML and it should work: 您在.append有一个错字(忘记添加正斜杠),修复了损坏的HTML ,它应该可以工作:

From: 从:

...Remove</a></td><tr>')

To: 至:

...Remove</a></td></tr>')

Use $(document) selector while appending dom, live and delegate not recommended. 不建议在附加dom, livedelegate时使用$(document)选择器。 For example : 例如 :

$(document).on('click','.removeAdmin',function(e){
    e.preventDefault();
     alert('clicked');
    alert(this.attr(id));
});

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

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