没有jQuery
我目前正在检查用户是否按下了元素。但是,当console.log
ging event.target
时,我看到一次点击发生在2个元素上(一个是输入元素,另一个是标签)。首先显示标签元素,这导致函数认为按下没有发生在输入元素上,因此点击发生在元素之外,但这不是真的。
我想检查印刷机是否在输入元素之外而不是标签的原因是因为有<span>
和其他元素在点击时被触发。
到目前为止我的代码:
document.addEventListener("click", function(event) {checkChecked(event); });
function checkChecked(inputEvent) {
if(inputElement !== inputEvent.target && !inputElement.contains(inputEvent.target)) {
console.log("click outside");
}
}
HTML:
<li class="payment-shipping-method checked">
<h3>
<input type="radio" name="paymentMethodId" id="payment-method-7-radio" class="payment-method" value="7" checked="">
<label for="payment-method-7-radio">
<span class="figure"><b><img src="img" alt=""></b></span>
<span class="caption">caption<span class="price zero">
<span class="amount">0</span>
<span class="currency"> kr</span>
</span><i>caption</i></span>
</label>
</h3>
<div class="description"></div>
</li>
我该怎么做?
答案 0 :(得分:1)
我对此进行了一些调查,发现这并不像我想象的那么容易,但仍有可能。在此编辑中值得注意:
addEventListener
行。由于checkChecked
像所有事件处理程序一样采用单个event
参数,因此我们可以直接引用它。inputEvent.target.closest("label")
来获取所点击元素的最近label
个祖先,但由于某种原因,该代码片段无效。我在getClosest
函数中快速重新创建了该功能。
document.addEventListener("click", checkChecked);
var inputElement = document.getElementById("payment-method-7-radio");
// For some reason, while I was building this snippet,
// I found the native Element.closest function was not
// working, and built this substitute
function getClosest(fromElement, toSelector) {
if (fromElement.matches(toSelector)) {
return fromElement;
}
if (fromElement === document.documentElement) {
return null;
}
return getClosest(fromElement.parentElement, toSelector);
}
function checkChecked(inputEvent) {
var closestLabel = getClosest(inputEvent.target, "label");
if (inputElement !== inputEvent.target &&
(!closestLabel || closestLabel.getAttribute("for") !== inputElement.id)) {
console.log("click outside");
return;
}
if (inputElement === inputEvent.target) {
console.log("clicked element");
}
if (closestLabel && closestLabel.getAttribute("for") === inputElement.id) {
console.log("clicked label");
}
}
<li class="payment-shipping-method checked">
<h3>
<input type="radio" name="paymentMethodId" id="payment-method-7-radio" class="payment-method" value="7" checked="">
<label for="payment-method-7-radio">
<span class="figure"><b><img src="img" alt=""></b></span>
<span class="caption">caption<span class="price zero">
<span class="amount">0</span>
<span class="currency"> kr</span>
</span><i>caption</i></span>
</label>
</h3>
<div class="description"></div>
</li>
答案 1 :(得分:0)
您正在为文档添加侦听器,因此将在任何单击
上调用回调用这个替换第一行,不要忘记修改选择器
document.querySelector('yourInputsSelector').addEventListener('click', checkChecked)