Force click with trigger() on closest div

2019-05-23 05:02发布

问题:

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>