簡體   English   中英

從父 div 的子級禁用單擊事件

[英]Disabling a click event from the child of a parent div

我正在嘗試將單擊事件添加到具有 class 父級的div中。 現在在那個div里面,我有一個帶有 class 子元素的div ,它有自己的點擊事件。

如何設法禁用該子元素的父 function 的單擊事件,以便執行子元素本身的 function?

我試過使用pointer-event:none; 但它似乎沒有工作。 為了更好地理解,我寫了一個 jsfiddle。

https://jsfiddle.net/arq1epbs/

 $(document).on('click', '.parent', function() { var url = $(this).attr("data-url") document.location.href = url });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent" data-url="www.google.com"> Im the parent <div class="child"> im the child and I don't want to go to Google </div> </div>

感謝您提前提供的所有幫助!

您可以使用stopPropagation()

 $(document).on('click', '.parent', function () {
    var url = $(this).attr("data-url")
    document.location.href = url 
});
 $(document).on('click', '.child', function (e) {
 e.stopPropagation();
});

由於它在堆棧片段中不起作用,這里有一個小提琴供參考: stopPropagation()

您可以簡單地在子點擊事件中調用event.stopPropagation() ,以防止事件在 DOM 樹中冒泡,從而防止任何父處理程序收到子點擊事件的通知,例如:

 $(document).on('click', '.parent', function() { //var url = $(this).attr("data-url") //document.location.href = url console.log('Parent Clicked'); }); $(document).on('click', '.child', function(event) { event.stopPropagation(); console.clear(); console.log('Child Clicked'); });
 .parent{background:#99c0c3;width:350px;height:120px;position:relative}.child{background:#ffde99;width:300px;height:50%;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%)}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent" data-url="www.google.com"> Im the parent <div class="child"> im the child and I don't want to go to Google </div> </div>

只需添加這一行:

 $(document).on('click', '.parent', function (e) { if(e.target;== this) return false. //This line added var url = $(this).attr("data-url") document.location;href = url });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent" data-url="www.google.com"> Im the parent <div class="child"> im the child and I don't want to go to Google </div> </div>

你可以在“純”JS中做到這一點

 document.querySelector('div.parent').onclick = evt => { if (.evt.target.matches('div.parent')) return // reject sub elements click document.location.href = evt.target.dataset.url }
 div.parent { cursor: pointer } div.child { cursor: default }
 <div class="parent" data-url="www.google.com"> Im the parent <div class="child"> Im the child and I don't want to go to Google </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM