there is some html code like this:
<ul>
<li id='root' class='tree-node'>
root
<ul>
<li class='tree-node' id='node1'>node1</li>
<li class='tree-node' id='node2'>node2</li>
<li class='tree-node' id='node3'>node3</li>
<li class='tree-node' id='node4'>node4
<ul>
<li class='tree-node' id='node4-1' >node4-1</li>
<li class='tree-node' id='node4-2' >node4-2</li>
</ul>
</li>
</ul>
</li>
<ul>
i want to bind click event to each tag which has tree-node class
and also binding click event to document
here is my code:
$(".tree-node").click(function(e){
console.log($(this).attr("id"));
});
$(document).click(function(e){
console.log("document clicked!");
});
Is there any alternative for stopPropagation() to stop event bubbling from node4-2 to its parents?
fiddle : http://jsfiddle.net/R6ySc/
You could just use the document click event and handle everything from there.
$(document).click(function(e){
console.log("document clicked!");
var t = $(e.target);
if(t.attr("class") == "tree-node") {
console.log("tree node clicked");
}
});
Check this fiddle: http://jsfiddle.net/R6ySc/3/
as an alternative, you can also specify a selector in the onclick event for the document (check the jQuery documentation for this):
$(document).on("click", ".tree-node", function(e) {
e.stopPropagation();
console.log("tree node '" + $(this).attr("id") + "' clicked");
});
for reference, check the comments below