2016-07-24 58 views

回答

3

可以使用event.target

例子:

$(document).ready(function() { 
 
    $("div").on("click", function(event) { 
 
    alert("You click on : " + event.target.tagName) 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div>this is Div 
 
    <p>This is p</p> 
 
</div>

+0

我不知道如何幫助,您可以詳細點嗎? 「不在這裏」的孩子可以有很多孩子,在這種情況下,event.target將是其中的一個,所以我不能簡單地比較一下event.target == .not.here。 – Lao

+1

你可以給div一個唯一的id/class/data屬性,並且可以通過event.target對象獲得,因爲這是實際點擊的dom元素...然後你可以知道屬性是你想要的,並觸發如果存在則採取行動,如果不存在則採取行動 – Stu

1
  • 將類分配給它們將成爲元素ignored
  • 使用.hasClass()來檢測rmine是否有任何匹配的元素被分配給定的類

$('#parent').on('click', function(event) { 
 
    if ($(event.target).hasClass('ignore')) { 
 
    alert("Ignore !"); 
 
    } else { 
 
    alert("Do something!"); 
 
    } 
 
});
#parent { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: blue; 
 
    color: white; 
 
} 
 
#child2 { 
 
    background-color: white; 
 
    color: red; 
 
    margin: 10px; 
 
} 
 
#child1 { 
 
    background-color: white; 
 
    color: green; 
 
    margin: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div id="parent">it should trigger here 
 
    <div id="child1">and here</div> 
 
    <div id="child2" class="ignore">but not here, and there are many of this kind</div> 
 
</div>

如果那裏設立ids它們將成爲ignored,使用event.target.id屬性和反對測試值!

$('#parent').on('click', function(event) { 
 
    if (event.target.id === 'child2' || event.target.id === 'child3') { 
 
    alert("Ignore !"); 
 
    } else { 
 
    alert("Do something!"); 
 
    } 
 
});
#parent { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: blue; 
 
    color: white; 
 
} 
 
#child2 { 
 
    background-color: white; 
 
    color: red; 
 
    margin: 10px; 
 
} 
 
#child3 { 
 
    background-color: white; 
 
    color: red; 
 
    margin: 10px; 
 
} 
 
#child1 { 
 
    background-color: white; 
 
    color: green; 
 
    margin: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div id="parent">it should trigger here 
 
    <div id="child1">and here</div> 
 
    <div id="child2">but not here, and there are many of this kind</div> 
 
    <div id="child3">but not here, and there are many of this kind</div> 
 
</div>