使函数仅影响onclick = function(this)中的“ this”对象

时间:2018-09-18 08:16:43

标签: javascript jquery

我想让一个函数只影响'this'对象!

但它也可以在以前单击的对象中使用。

我该怎么办?

它显示在此▼

function toggle(obj, className) {
  obj.classList.toggle(className);
  $('.box').on('click', function(e) {
    e.stopPropagation();
    obj.classList.toggle(className);

  })
}
.btn-toggle.on {
  background: #000;
  color: #fff;
}

.box {
  width: 100px;
  height: 100px;
  background: red;
}

.box.on {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button class="btn-toggle" onclick="toggle(this,'on')">toggle</button>
<button class="btn-toggle" onclick="toggle(this,'on')">toggle</button>
<div class="box"></div>

1 个答案:

答案 0 :(得分:1)

您必须取消绑定先前添加的点击事件,请检查以下代码:

function toggle(obj, className) {
$('.box').off( "click");//Unbind previously added event
  obj.classList.toggle(className);
  $('.box').on('click', function(e) {
    e.stopPropagation();
    obj.classList.toggle(className);

  })
}
.btn-toggle.on {
  background: #000;
  color: #fff;
}

.box {
  width: 100px;
  height: 100px;
  background: red;
}

.box.on {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button class="btn-toggle" onclick="toggle(this,'on')">toggle</button>
<button class="btn-toggle" onclick="toggle(this,'on')">toggle</button>
<div class="box"></div>