how to define condition with clicked objet's parent?

别等时光非礼了梦想. 提交于 2019-12-12 04:04:07

问题


i cant access clicked object(this) parent's class.. click same elements and different returns?

this is DEMO

HTML

<div class="rows row1">
  <div class="ele">1</div>
  <div class="ele">1</div>
  <div class="ele">1</div>
</div>

<div class="rows row2">
  <div class="ele">2</div>
  <div class="ele">2</div>
  <div class="ele">2</div>
</div>

jQuery

$('.ele').click(function() {

  if ( $(this).parent().hasClass('r1') ) {//way1
    alert('you clicked 1st row element');
  }

  else if ( $(this).parent().hasClass('r2') === true ) {//both way wont work
    alert('you clicked 2nd row element');
  }

});


回答1:


Because both parent have no r1 or r2 class, that should be row1 and row2:

$('.ele').click(function() {

  if ( $(this).parent().hasClass('row1') ) {
    alert('you clicked 1st row element');
  }

  else if ( $(this).parent().hasClass('row2')) {
    alert('you clicked 2nd row element');
  }

});

demo here



来源:https://stackoverflow.com/questions/11278326/how-to-define-condition-with-clicked-objets-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!