开发者

How to attach jquery to click() event when HTML is generated dynamically?

开发者 https://www.devze.com 2023-01-10 05:06 出处:网络
I am using the JQUeryUI to present a Dialog Box to the end user and populating it with dynamically generated HTML like this.

I am using the JQUeryUI to present a Dialog Box to the end user and populating it with dynamically generated HTML like this.

$('#listusers').click(function() {
    $("#dialog").html("");
    $("#dialog").attr("title", "Existing Users");
    $("#dialog").load("service/get.aspx?data=users", $(function(data) { $("#dialog").dialog({ modal: true }); }));
});

The HTML that is returned from "service/get.aspx?data=users" looks like this.

<div class="ui-widget" id="users-contain">
    <h1>Existing Users:</h1>
<table class="ui-widget ui-widget-content" id="users">
    <thead>
        <tr class="ui-widget-header">
            <th>Act</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <a href="#" class="deleteuser" id="0delete">
                    <img src="images/49.gif" alt="help">
                </a>
            </td>
            <td id="0username">JoePlumber</td>
            <td>joe@mcain2008.org</td>
        </tr>
        <tr>
            <td>
                <a href="#" class="deleteuser" id="1delete">
                    <img src="images/49.gif" alt="help">
                </a>
            </td>
            <td id="1username">SarahPalin</td>
            <td>sarah@cliffnotes.com</td>
            </tr>
    </tbody>
</table>
</div>

My question is if I want to attach some jquery to the click event of all elements with a class of deleteuser like this

$(".deleteuser").click(function() {
        alert('help');
    });  

Where do I put this code?

I tried like this but no luck

$('#delete-user').click(function() {
    $("#dialog").html("");
    $("#dialog").attr("title", "Existing Users");
    $("#dialog").load("service/get.aspx?data=users", $(functi开发者_Python百科on(data) { $("#dialog").dialog({ modal: true }); }));
    $(".deleteuser").click(function() {
        alert('help');
    });
});


in your main document.ready function, add this:

$(".deleteuser").live('click',function() {
        alert('help');
    });  

live() binds the event to all occurence of the selector, including those that are not present at the time of the function call, meaning, for all elements called via ajax. See the doc


use live binding - http://api.jquery.com/live/

$(".delete-user").live("click", function(evt){
       [ do stuff ]
});

0

精彩评论

暂无评论...
验证码 换一张
取 消