jQuery .click() problem

余生长醉 提交于 2019-12-25 00:08:47

问题


I hava a simple jQuery script. I use .ajax() to get some info from my database, it works perfect.

The problem is the php-code genereate xhtml code with a-tags with different class, like .info, .delete and .edit.

I want to do stuff when i click in my .info link. I have tried this code:

$('a.info').click(function (e) {
    e.preventDefault(); 
    alert('Do stuff');
});

it dosen't work at all, nothin happens. firebug gives me no error so i dont know how to solve the problem.

    $('a').click(function (e) {
    e.preventDefault(); 
    alert('Do Stuff 2');
});

works on all links on the site but not on the link that is generated from the php code.

my code:

$(function(){       
$.ajax({
    type: "POST",
    url: 'users.php',
    data: 'getall=true',
    success: function( r ) { 
        $(' #content ').html( r );
    },
    error: function( ) {
        alert('Error');
    }
});

$('a.info').click(function (e) {
    e.preventDefault(); 
    alert('Do Stuff');
});


$('a').click(function (e) {
    e.preventDefault(); 
    alert('Do Stuff 2');
});

});


回答1:


Use .live

$('a.info').live('click', function (e) {
    e.preventDefault(); 
    alert('Do stuff');
});


$('a').live('click', function (e) {
    e.preventDefault(); 
    alert('Do Stuff 2');
});



回答2:


Use $.live. $.click registers the click events on objects that are currently present. Using $.live means your click events are basically re-registered when new elements are added to the page.




回答3:


It looks like you're getting the HTML from the AJAX request. The click function will set up handlers for the objects that it knows about at the time you call - in this case, it is after the DOM is loaded but before the AJAX request is returned.

To handle the click event for any object that is added after the DOM is loaded, use the live function:

$('a.info').live('click', function (e) {
    e.preventDefault(); 
    alert('Do stuff');
});


来源:https://stackoverflow.com/questions/4968181/jquery-click-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!