StopPropagation 允许点击父节点

StopPropagation allowing click on parent

我有以下代码,其中我有一个标签,我可以在其中阻止默认操作,这样我就可以在单击而不是输入时专注于可编辑范围。但是,如果用户点击跨度,我希望它忽略绑定到父级的点击事件,所以我使用 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');
  })