尽管被设置为删除,类仍会切换一次

时间:2016-08-20 20:02:51

标签: javascript jquery html

当我点击div中的图像时,它会切换它的类一次,我根本不希望它这样做,我只是想让它切换父div的类。如何阻止它一起切换?



# Generate Instagram API
Instagram_api = InstagramAPI(access_token=Instagram_ACCESS_TOKEN,
                  client_id=Instagram_CLIENT_ID,
                  client_secret=Instagram_CLIENT_SECRET)

# try media_search method
media_search = Instagram_api.media_search(q="food", count=10, lat=47.6038321, lng=-122.3300623, distance=5000)

// .item
function swap() {
    $('#' + event.target.id).toggleClass('selected');

  }
  // .boop

function swapDad() {
  var par = $('#' + event.target.id).parent().attr('id');
  $('#' + par).toggleClass('selected');
  $('#' + event.target.id).removeClass('selected');

}

#itemz {
  border: solid 1px black;
}
.item {
  margin: 5px;
  border: white 3px solid;
  background-color: grey;
  width: 125px;
  height: 150px;
  text-align: center;
  vertical-align: bottom;
  display: inline-block;
}
.selected {
  border: green 3px solid;
}
.boop {
  width: 100px;
  height: 100px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-top: 10px;
  margin-bottom: 10px;
}




1 个答案:

答案 0 :(得分:0)

当您点击图片时,点击事件也会传播到包含它的DIV,因此它会调用swapDad(),然后调用swap()。如果您只想切换DIV的课程,则不需要onclick="swapDad()"中的img

而不是使用非标准且在所有浏览器中都不可用的全局变量event,您应该将该元素作为参数传递给函数。



// .item
function swap(div) {
    $(div).toggleClass('selected');
}

#itemz {
  border: solid 1px black;
}
.item {
  margin: 5px;
  border: white 3px solid;
  background-color: grey;
  width: 125px;
  height: 150px;
  text-align: center;
  vertical-align: bottom;
  display: inline-block;
}
.selected {
  border: green 3px solid;
}
.boop {
  width: 100px;
  height: 100px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-top: 10px;
  margin-bottom: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="itemz">
  <div class="item" id="1" onclick="swap(this)">
    <img src="http://placehold.it/100/000/fff?text=test" class="boop" id="img1">Something
  </div>
  <div class="item" id="2" onclick="swap(this)">
    <img src="http://placehold.it/100/000/fff?text=test2" class="boop" id="img2">Something
  </div>
</div>
&#13;
&#13;
&#13;