i have a link when clicked it creates a div with another link inside it i want to disable the new link tried many solutions like preventDefault and return false but didn’t work and here’s the example http://jsfiddle.net/2RSJj/1/:
$(document).ready(function(){
$("a[title='go']").click(function(e){
$(".cities").append("<div class='city'><a href='http://www.google.com' class='mylink'>google</aiv>");
e.preventDefault();
});
$(".cities .city a").click(function(e){
e.preventDefault();
alert($(this).attr("class"));
});
});
main html :
<a href="#" title="go">go</a><p>
<div class="cities">
</div>
As the link is dynamically added, you should use the
on()method (assuming jQuery >= 1.7; jQuery < 1.7 should usedelegate()) to prevent the default action of said link:JS Fiddle demo.
The problem you were having is that the link isn’t present when the event-binding happens, therefore the
click()method doesn’t bind theclickevent to the relevantaelement. Withon(), theclickis attached to a parent/ancestor element (that exists at the point of event-binding), and then listens for that event (the'click'string in the first argument) being fired on an element that matches the selector (passed as the second argument).Assuming that both the event and the selector match (the
a.mylinkelement isclick-ed), then the function is executed, which in this case simply prevents the default action being fired. It is, though, important to note that with delegated events you cannot simplyreturn false, because the event has, by definition, already been fired by the time it’s propagated/bubbled up to the ancestor element to which the event is bound.Also, if an element between the two elements has an event handler that explicitly implements
return falsethen the event delegation won’t progress past that element (since theclickwill propagate/bubble to the element with the handler, which will respond with thereturn false(a combination ofevent.stopPropagation()andevent.preventDefault()).For example, in the following code, I’m using the
html:In this case the
on()method remains attached to the.citieselement, but the.demoelement has a click-handler which simply, as you might imagine, returnsfalse:JS Fiddle demo.
In the above note that there is no alert fired when clicking the
a.mylinkelement, whereas without thatclick-handler intercepting (and negating) theclickevent, thealert()is fired:JS Fiddle demo.
So, be aware of those events bound to your elements when using delegation. It can be tricky (ish), when starting.
Reference:
delegate().on().