jquery button not respond to click method

坚强是说给别人听的谎言 提交于 2019-12-09 18:49:47

问题


so i am dynamically rendering a paragraph with jquery using the append method and i want to add a click event to it but for some reason the click event is not working, i know the solution is probably simple but I am new to jquery and would appreciate any help...I know the code inside the function works because i tested it with a static button, it is just not working with the dynamic one..Thanks in advance for any help,

here is my code

$(this).parent().parent().children("div").append("<p class='tryAgain'>Try Again</p>");

the click function code,

$(".tryAgain").click(function() {......}

回答1:


Anything you add to the DOM after the document.ready has fired needs to use .live or .delegate in order to add an event handler to the newly added element.

For instance:

$('.tryAgain').live("click", function() {...});

If you are using jquery 1.7+ you should use .on:

$(document).on("click", ".tryAgain", function(){ ... });



回答2:


Try with $.live o $.delegate.




回答3:


Use:

$('.tryAgain').live('click', function()
{
  ....
});



回答4:


There is an alternative to use live events, you can add the handler when you create the element like this:

$("<p>Try Again</p>", {
  "class": "tryAgain",
  click: function(){
     //YOUR CLICK HANDLER
  }
}).appendTo($(this).parent().parent().children("div"));



回答5:


I think you can attach a click event right there when you create the new p tag like this:

$(this).parent().parent().children("div").append(
    $('<p>').addClass('tryAgain').click(function(){
        alert('test');
    }));


来源:https://stackoverflow.com/questions/8142223/jquery-button-not-respond-to-click-method

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