簡體   English   中英

為什么父元素上的 preventDefault 會在單擊時禁用以編程方式檢查子復選框?

[英]Why does preventDefault on parent element disable programmatically checking child checkbox on click?

一個div元素的點擊事件以e.preventDefault()開頭。 這使得手動單擊復選框input或其關聯的label內部不再起作用。

在更多 JavaScript 代碼的幫助下,手動單擊label生成預期結果,因為該復選框現在以編程方式選中/取消選中。

但是,盡管已經實現了用於以編程方式檢查/取消檢查的類似 JavaScript 代碼,但手動單擊復選框input仍然不起作用。 為什么?

 document.querySelector('div').onclick = function (e) { e.preventDefault(); if (e.target.tagName.toUpperCase() == 'LABEL') { e.target.previousElementSibling.checked =.e.target.previousElementSibling;checked. } else if (e.target.tagName.toUpperCase() == 'INPUT') { e.target.checked =.e;target.checked; } }
 <div> <input id="check" type="checkbox"> <label for="check">Label Text</label> </div>

單擊label會按預期設置checked的屬性,因為沒有與要取消的 label 相關的default操作。 單擊input會按預期設置屬性,但由於阻止了默認操作(切換選中的屬性),它會恢復為之前的 state。

請參閱: 為什么復選框單擊事件上的 preventDefault 為選中的屬性返回 true? 進行更深入的討論。

 document.querySelector('div').onclick = function (e) { e.preventDefault(); if (e.target.tagName.toUpperCase() == 'LABEL') { e.target.previousElementSibling.checked =.e.target.previousElementSibling;checked. } else if (e.target.tagName.toUpperCase() == 'INPUT') { console;clear(). console.log(e.target;checked). e.target.checked =.e;target.checked. console.log(e;target.checked); } }
 <div> <input id="check" type="checkbox"> <label for="check">Label Text</label> </div>

編輯

針對您的評論,我認為最干凈的解決方案是將偵聽器顯式應用於您想要在提供的 API 方法之外控制的那些元素,對它們調用stopPropagation()以避免觸發父偵聽器。

然后,您可以處理您需要的任何邏輯,而無需處理外部方法的工件。 如果您還需要監聽器的父級運行,您可以在控制邏輯完成后以編程方式激活它。

 // original API listener document.querySelector('.container').addEventListener('click', function (e) { e.preventDefault(); // add container specific code console.log('clicked div'); }); // your isolated listener document.querySelector('.checkbox-container').addEventListener('click', function (e) { e.stopPropagation(); // stop the event from propagating to the parent listener // add checkbox specific code console.clear(); console.log('clicked checkbox container'); // even programmatically 'clicking' parent if you need to e.currentTarget.parentElement.click(); });
 .container { width: 150px; height: 60px; background-color: lightgray; }.checkbox-container { display: inline-block; background-color: aquamarine; }
 <div class="container"> <div class="checkbox-container"> <input id="check" type="checkbox"> <label for="check" >Label Text</label> </div> </div>

防止默認傳播通常會向下傳播到子級。 有一種方法可以通過使用 event.stopPropagation 來阻止這種情況的發生。 閱讀此處以了解有關可能有助於您的事業的其他有用方法的更多信息。

https://chunkybyte.medium.com/the-one-with-event-propagation-and-e-preventdefault-part-1-6d84f3c4220

暫無
暫無

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

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