Reputation: 7969
I came across a strange problem with html anchor tags. I have an anchor tag on the html page and on clicking the 'a' tag it is supposed to give me an alert message. It is working well. But, If I append a new 'a' tag using jquery to the html page and on click of that appended 'a' tag is not working. i was able to give href, target blah blah blah to the appending 'a' tag but.. onlick function is not working. Any thoughts ???
Thanks in advance.
Upvotes: 0
Views: 4415
Reputation: 43410
In jQuery, you typically use the .click() function on a selector to set the click handler. Note that if multiple items match the selector, multiple items will have the click handler installed.
Here's a trivial code snippet that should do what you want:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function addLink(label, msg) {
/* Create link element.
The href="#" makes the link act like a link
(be highlighted, selectable, etc.).
The onClick="return false;" keeps the link from
scrolling the browser to the top of the page.
The onClick is not interfered with by jQuery's
.click() . */
var link = $('<a href="#" onClick="return false;">' + label + '</a>');
/* Install click handler. */
function clicked_handler() {
alert(msg);
}
link.click(clicked_handler);
/* Add the link to the body. */
$('body').append(link);
}
addLink('Link 1', 'You clicked link 1');
$('body').append('<br/>');
addLink('Link 2', 'You clicked link 2');
</script>
</body>
</html>
Upvotes: 1
Reputation: 16905
Adding an event works on stuff that is already on the page. If You add something aferwards You have to bind a new click eventto this new thing or use live, which always should be the second option
so instead of doing
$(something).append('<a href="" etc. ');
try something like this
$('<a></a>').attr('href','some url here').bind('click',function(){}).appendTo('body');
Upvotes: 0
Reputation: 25159
Try using this:
$("a").live("click", function(){
alert("Tadah!");
});
Upvotes: 0
Reputation: 888177
Your question is unclear.
I assume that you're adding a click handler to the <a>
tags by writing $('a.whatever').click(function() { ... })
, then adding new <a>
tags to the document.
When you write $(...).click(...)
, it only adds handlers to the elements that were found by the $(...)
at the time you added the handler. It will not apply to any elements you add later.
You're probably looking for jQuery's live
method, which will handle an event for all elements that match a selector, no matter when they were created.
For example:
$('a.whatever').live('click', function(e) { ... });
Upvotes: 0