jQuery - click() not working when attached to anchor created in PHP
I have this PHP code which outputs HTML anchor elements on a page:
if(!$isOnOwnPage)
echo '<a id="message-button" class="button">Message</a>';
if($isOnOwnPage)
echo '<a id="add-img-button" class="button">Add Image';
else if(!$isFollowing)
echo '<a id="follow-button" class="button">Follow';
else
echo '<a id="follow-button" class="button">Unfollow';
echo "</a>";
When I load the web page, I get this, as expected:
...
<a id="message-button" class="button">Message</a><a id="follow-button" class="button">Unfollow</a>
...
But when I try to attach a click() function to it, the clicking doesn't work. This is the jQuery code. (It's weird because all of my other JS on the page works flawlessly."
$('.button').click(function() { alert("HEY"); }); // It doesn't work grabbing by #follow-button or #message-button either.
What did I do wrong here? I've spent an hour lo开发者_开发问答oking at these snippets of code to no avail.
Try this:
$('.button').live('click',function() { alert("HEY"); });
Put it in your $(document).ready
function.
Gonna go out on a limb and guess that you've forgotten to wait for document.ready
and that the a.button
element doesn't exist when the click
event is bound.
Is ajax included somehow? Because then you need to either use the live, or re-apply the function.
It should work regardless if it's PHP generated. In the end it's still HTML that gets output to the client.
I think you should make sure that the JS code gets to the part where you assign clicks to the buttons. Maybe there's not document ready or a correct one. Maybe there's a boolean IF that doesn't get passed.
All in all, if you can see the code in the View Source page, then it's a HTML/JS problem, not a PHP one.
This is an old question, but to all there who want to add listeners to dynamic content, instead of using $('a').(click(function(){})
or $('a').on('click',function(){})
, you need to use instead the document as the object you want to attach the listeners, because the tag you are inserting wasn't in the DOM when the listener was assigned.
So instead you should use:
$(document).on('click','a',function(){ ... });
精彩评论