StopPropagation允许点击父级

时间:2018-01-10 15:09:10

标签: javascript jquery stoppropagation

我有以下代码,其中我有一个标签,我在其中阻止默认操作,以便在单击它而不是输入时我可以专注于可编辑范围。但是,如果用户点击了span,我希望它忽略绑定到父级的click事件,因此我使用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>
&#13;
&#13;
&#13;

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

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

中的输入

1 个答案:

答案 0 :(得分:1)

您还需要将preventDefault()stopPropagation()一起添加。

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