防止目标上的事件及其父级

时间:2015-07-07 10:12:00

标签: javascript

我有这个代码用于从具有此类名的每个元素中删除类名“joker”:http://jsfiddle.net/ffz30knn/1/

是否可以(仅限vanilla JS)阻止目标元素上的此事件及其父元素,因此当我单击<span class="joker">one</span>内的<div class="joker"></div>时,它将删除“joker”类具有此类但不是来自此span元素的其他元素,它是否包装div?

感谢。

以下是当前代码:

function removeClass(classToRemove) {
  var elems = document.getElementsByClassName(classToRemove);
  console.log(elems.length);
  if (!elems) return;
  for (var i = elems.length - 1; i >= 0; i--) {
    var elem = elems[i];
    elem.className = elem.className.replace(/(?:^|\s)joker(?!\S)/g, '');
  }
}
window.onload = function() {
  document.onclick = function() {
    removeClass("joker");
  };
};
div {
  background: silver;
  padding: 3px 8px;
  margin: 5px;
}
span {
  background: blue;
  padding: 3px 8px;
  color: white;
}
.joker {
  background: black;
  color: red;
}
<div class="one two three joker"><span class="joker">one</span>
</div>
<div class="one two three"><span>two</span>
</div>
<div class="one two three joker"><span class="joker">three</span>
</div>
<div class="one two three"><span>four</span>
</div>

2 个答案:

答案 0 :(得分:1)

如果我理解你要从每个元素中删除类joker但是你点击的那个元素?

removeClass功能中,您可以检查它是否是相同的元素

function removeClass(classToRemove) {
  var elems = document.getElementsByClassName(classToRemove);
  console.log(elems.length);
  if (!elems) return;
  for (var i = elems.length - 1; i >= 0; i--) {
    var elem = elems[i];
    if(elem != this)
        elem.className = elem.className.replace(/(?:^|\s)joker(?!\S)/g, '');
   }
}

我猜你可以通过Element.parentElement检查父元素,这样就可以了:

if(elem != this && elem != this.parentElement)

答案 1 :(得分:1)

您可以通过onclick事件获取您点击的元素:

window.onload=function() {
    document.onclick=function(event) {
        removeClass(event.target, "joker");
    };
};

将它传递给你的功能,你应该能够达到你想要的效果。

function removeClass(skip, classToRemove){
    var elems = document.getElementsByClassName(classToRemove);
    if (!elems) return;
    for (var i=elems.length-1;i>=0;i--) {
        var elem = elems[i];
        if (elem == skip || elem == skip.parentElement) {
           return
        } else {
            elem.className = elem.className.replace( /(?:^|\s)joker(?!\S)/g,'' ); 
        }
    }
}

此处更新了fiddle