Force click with trigger() on closest div

萝らか妹 提交于 2019-12-10 11:09:43

问题


Hi I've got follow code:

$('.myInput').click(function() {
  $('.addon').trigger('click');
});

$('.addon').click(function() {
  console.log("Clicked");
});
.wrapper {
  display: flex;
  flex-direction: column;
}
.inputWithAddon {
  display: flex;
  margin-bottom: 10px;
}
input {
  height: 20px;
}
.addon {
  width: 26px;
  height: 26px;
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="inputWithAddon">
    <input class="myInput">
    <div class="addon"></div>
  </div>
  <div class="inputWithAddon">
    <input class="myInput">
    <div class="addon"></div>
  </div>
  <div class="inputWithAddon">
    <input class="myInput">
    <div class="addon"></div>
  </div>
</div>

I would like to force a click with trigger() on my green div, when I clicked in the input. This should be on the div from the current clicked input (on the right side). At the moment, it calls the click for all the green divs (look at console). I would like just to do this for the div of the clicked input. I tried closest():

$(this).closest('.addon').trigger('click');

It didn't work.

Any ideas?

Thanks.


回答1:


Try using the sibling property of Jquery

$(this).siblings('.addon').trigger('click');



回答2:


A possible soln would be:

$(this).parent().find('.addon').trigger('click');

or as @Mohammad mentioned shortest:

$(this).next().trigger('click');

or as @Deepak Singh answered:

$(this).siblings('.addon').click();

or as @freedomn-m mentioned a (more) layout independant solution:

$(this).closest(".inputWithAddon").find(".addon").click();

$('.myInput').click(function() {
  $(this).next().trigger('click');
});

$('.addon').click(function() {
  console.log("Clicked");
});
.wrapper {
  display: flex;
  flex-direction: column;
}
.inputWithAddon {
  display: flex;
  margin-bottom: 10px;
}
input {
  height: 20px;
}
.addon {
  width: 26px;
  height: 26px;
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="inputWithAddon">
    <input class="myInput">
    <div class="addon"></div>
  </div>
  <div class="inputWithAddon">
    <input class="myInput">
    <div class="addon"></div>
  </div>
  <div class="inputWithAddon">
    <input class="myInput">
    <div class="addon"></div>
  </div>
</div>


来源:https://stackoverflow.com/questions/38302447/force-click-with-trigger-on-closest-div

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