I have the following html:
<ul class="treeList2">
<li class="topLevel marked checked"><div class="tlWrap clearfix"><input type="checkbox" checked="checked" class="checkbox"><strong>Level name here blah blah <span>(3)</span></strong></div></li>
...
<script type="text/javascript">
/*<![CDATA[*/
$(function(){
$('.treeList2 li.topLevel .tlWrap').click(function(){
alert(this);
});
});
/*]]>*/
</script>
The problem is that this fires when I click the checkbox (which i don't want). I Only want to alert(this) when the 'div' is clicked (I do this so that I can change the div background). thanks
You can prevent the click event on the checkbox from bubbling up to the parent like this:
$('.checkbox').click(function(e){
e.stopPropagation();
});
check if the target is not input element and then only alert.
$(function(){
$('.treeList2 li.topLevel .tlWrap').click(function(e){
if (e.target.nodeName !== 'INPUT') {
alert(this);
}
});
});
Looking at it, you need to call the parent?
$('.treeList2 li.topLevel .tlWrap').parent().click( ...
Although if you want to change the parent div when the checkbox is clicked:
$('.treeList2 li.topLevel .tlWrap').click(function(){
$(this).parent().css('background-color','red');
});
[edit] Sorry, I mis-read the html. There's a 'not' function that you can exclude elements with:
$('.treeList2 li.topLevel .tlWrap').not('input').click( ...
This will fire when anything in the div is clicked on, except the checkbox.
You can check whether the element that triggered the event (e.target) has a class of tlWrap
.
$(function(){
$('.treeList2 li.topLevel .tlWrap').click(function(e){
if($(e.target).hasClass("tlWrap")) {
alert(this);
}
});
});
See a working demo .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.