gpt4 book ai didi

javascript - 用于否定父元素中特定 HTML 元素的 JQuery 选择器

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:13 24 4
gpt4 key购买 nike

我有一个由 JQuery 多选下拉库生成的 HTML 标签结构,如下所示:

<label for="ui-multiselect-selectedSku-option-1"><input id="ui-multiselect-dropdown-option-1" type="radio" value="DropDownVal1"><span>DropDownText1</span></label>
<label for="ui-multiselect-selectedSku-option-2"><input id="ui-multiselect-dropdown-option-2" type="radio" value="DropDownVal2"><span>DropDownText2</span></label>

我的要求是:除了 input 元素,每当用户点击

<label></label>

(包括标签)区域,我需要做event.preventDefault() .我试过了

 $(document).on('click', 'label[for^="ui-multiselect-selectedSku-option-"]',function(event){
event.preventDefault();
});

但即使我点击 <input> 也会触发上述处理程序也在标签内(这很明显,我知道!)

我如何编写一个 JQuery 选择器来过滤它。

最佳答案

最好的办法是让输入脱离标签...但是:

I do not have control over this markup structure... (your comment on another answer)

您可以使用 .stopImmediatePropagation() <input> 上元素...所以点击事件不会冒泡到标签。

见下文...尝试点击标签,然后点击 radio 。

$(document).on('click', 'label[for^="ui-multiselect-selectedSku-option-"]',function(event){
console.log("Clicked on a label");
event.preventDefault(); // Don't know if that is useful...
});

$(document).on('click', 'label[for^="ui-multiselect-selectedSku-option-"] input',function(event){
console.log("Clicked on a radio input");
event.stopImmediatePropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="ui-multiselect-selectedSku-option-1"><input id="ui-multiselect-dropdown-option-1" type="radio" value="DropDownVal1"><span>DropDownText1</span></label>
<label for="ui-multiselect-selectedSku-option-2"><input id="ui-multiselect-dropdown-option-2" type="radio" value="DropDownVal2"><span>DropDownText2</span></label>

关于javascript - 用于否定父元素中特定 HTML 元素的 JQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55067302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com