JS 单击事件捕获到 SVG 而不是按钮

JS Click Event Capturing down to SVG instead of button

当我在按钮上创建点击事件侦听器时,如果在按钮内点击 SVG,事件目标是 <use xlink:href="#star-filled"></use> 而不是注册到点击事件的元素。

如何防止它捕获 child 作为目标元素?

HTML

<button type="button" class="rp-form-rating-btn">
  <svg class="rp-star-icon rp-star-four" data-rating="4">
    <use xlink:href="#star-filled"></use>
  </svg>
</button>

JavaScript

var stars = document.querySelectorAll('.rp-form-rating-btn');

for (var i = 0; i < stars.length; i++) {
   stars[i].addEventListener('click', event => {
     console.log(event.target);
   }, false);
}

使用 currentTarget 而不是 target 来捕获 button 而不是 svg

currentTarget 将允许您获得您点击的 element

From MDN: currentTarget always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

现场演示:

var stars = document.querySelectorAll('.rp-form-rating-btn');

stars.forEach(function(stars) {
  stars.addEventListener('click', function(event) {
    console.log(event.currentTarget);
  }, false);
})
<button type="button" class="rp-form-rating-btn">
  <svg class="rp-star-icon rp-star-four" data-rating="4">
    <use xlink:href="#star-filled"></use>
  </svg>
</button>