[英]stop click event propagation when clicked inside anchor tag on a div
說明:
我有以下HTML
<a href = "go some where">
<div onclick = "myfunc1(....)">CLICK ME A</div>
<div onclick = "myfunc2(....)">CLICK ME B</div>
</a>
現在,當我單擊第一個div時,將觸發錨標記,第二個div也將被觸發。.我希望能夠單擊錨標記內的任何div,它應該只調用分配給它的函數...
當且僅當我不單擊任何div但整個其他區域的定位標記都具有時,才應將我帶到href具有的頁面...
我試過了什么:
$(".add_this_person").on("click", "a", function (e) {
e.preventDefault();
} ); // where add_this_person is a class of both divs
您可以嘗試以下方法:
將class
添加到div並更改jQuery
代碼,如下所示:-
$(".add_this_person").on("click", "a", function (e) {
e.preventDefault();
if($(e.target).is('.first'))
{
alert("A");
}else if($(e.target).is('.second'))
{
alert("B");
}else{
window.location=$(this).attr('href');
}
});
您的嘗試還可以,但是您可以使用jQuery的全部功能,而無需在div中使用“ onclick”事件。 只需分配一個類並創建一個類事件,該事件將針對給定類的所有元素觸發並將目標函數存儲在額外的屬性中...
只需將div標簽與操作“ my-action”一起放置,並將目標函數存儲在以函數名稱為目標的HTML數據桶“函數”中。
<div class="my-action" data-function="myAction1" >CLICK ME A</div>
<div class="my-action" data-function="myAction2">CLICK ME B</div>
<script type="text/javascript">
$(document).ready(function() {
//Declare your functions here, add them to window[] array...
window.myAction1 = function() {
alert("A");
}
window.myAction2 = function() {
alert("B");
}
//This will trigger whenever an element with class "my-action" is clicked...
$(document).on("click", ".my-action", function (e) {
//Just read the function name from data-function and assign it from window[] array
var targetFunction = window[$(this).data("function")];
//And execute it, done!
targetFunction();
});
});
</script>
創建了一個有效的小提琴... http://jsfiddle.net/Lnnffcx5/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.