gpt4 book ai didi

javascript - StopPropagation 允许点击父节点

转载 作者:行者123 更新时间:2023-11-29 15:16:58 27 4
gpt4 key购买 nike

我有以下代码,其中我有一个标签,我可以在其中阻止默认操作,这样我就可以在单击而不是输入时专注于可编辑范围。但是,如果用户单击跨度,我希望它忽略绑定(bind)到父级的单击事件,因此我使用 stopPropagation

但是,它似乎不起作用,父点击事件仍然被触发:

var $quantitySpan = $('.quantity-span'), 
$quantityTextbox = $('.textbox'),
$quantityHolder = $('.product-checkbox__quantity');

$quantitySpan
.on('click', e => {
e.stopPropagation(); // I thought this would stop the bubbling up to the parents click event
console.log('span clicked');
})
.on('keyup', () => {
$quantityTextbox.val($quantitySpan.text());
})
.on('blur', () => {
const textVal = $quantitySpan.text();
if (isNaN(textVal) || textVal === '') {
$quantitySpan.text("0");
$quantityTextbox.val("0");
}
});

$quantityHolder.on('click', (e) => {
e.preventDefault();
console.log(e.target, e.currentTarget); // this seems to suggest that the target is the label that has been clicked allthough it changes the target to the input and not the span (even though I have prevented the default action of the label and stopped propagation on the span)
});
* {
box-sizing: border-box;
}

.product-checkbox__quantity {
display: block;
padding-top: 1rem;
}

.product-checkbox__quantity-holder {
margin-top: 0.5rem;
display: flex;
flex-direction: row;
border: 1px solid #c6c6c6;
background: #FFF;
border-radius: 5px;
padding: 1rem 1.25rem;
width: 100%;
overflow: hidden;
position: relative;
}

.product-checkbox__quantity-holder .off-screen {
position: fixed;
left: 105%;
top: 125%;
border: 0;
outline: 0;
}

.product-checkbox__quantity-holder .quantity-span {
outline: none;
flex-shrink: 1;
padding-right: 0.5em;
max-width: 80%;
white-space: nowrap;
overflow: hidden;
}

.product-checkbox__quantity-unit {
flex-grow: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="product-checkbox__quantity">
Quantity:
<br>
<span class="product-checkbox__quantity-holder">
<input type="text" name="Quantities[VARIANT2]" autocomplete="off" class="product-checkbox__quantity-input textbox off-screen" id="quantity-variant2" value="0" data-unit="m2" data-rule-required="true" data-msg-required="required" data-rule-integer="true" data-msg-integer="Integers only"><span class="quantity-span" contenteditable="true">0</span>
<span class="product-checkbox__quantity-unit">m<sup>2</sup></span>
</span>
<span class="field-validation-valid" data-valmsg-for="quantity-variant2" data-valmsg-replace="true"></span>
</label>

我如何更改上面的代码,以便当您单击 0 时,它会注册为单击跨度而不是标签/输入(或者我如何看到我在标签单击事件中单击了跨度)

奇怪的是,如果你检查 0,它说它是跨度,所以不确定为什么目标更改为 console.log 中的输入

最佳答案

您还需要添加 preventDefault()stopPropagation()

$quantitySpan
.on('click', e => {
e.stopPropagation();
e.preventDefault();
console.log('span clicked');
})

关于javascript - StopPropagation 允许点击父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190390/

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