简体   繁体   中英

jQuery click link when another is clicked

I have an element like this

I want mylink2 to also be clicked whenever somebody clicks on mylink

To start I am trying to get the parent container on click like this

  $("#mylink").click(function(){ parentcontainer = this.closest('.myelement'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myelement"> <div class="container"> <div class="testitem"> <a id="mylink" href="#"> Test Link 1 </a> </div> </div> <div class="container"> <a id="mylink2" href="#"> Test Link 2 </a> </div> </div> 
But now I am stuck trying to click mylink2 am I on the right track?

You can use closest to get the parent and then find second element and trigger click command but since you have ids maybe you can use them for selecting elements. Keep in mind that id's must be unique.

 $("#mylink").click(function() { const parent = $(this).closest('.myelement'); parent.find('#mylink2').trigger('click') }); $("#mylink2").on('click', function() { console.log('click link 2') }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myelement"> <div class="container"> <div class="testitem"> <a id="mylink" href="#"> Test Link 1 </a> </div> </div> <div class="container"> <a id="mylink2" href="#"> Test Link 2 </a> </div> </div> 

you can trigger the jQuery first click to trigger the second one this way: $("#mylink").click(function(){ $("#mylink2").click(); });

taking in cosider that #mylink2 has some kind of a click handler function

If your links have ids the easiest way would be to use these ids:

 $('#mylink').on('click', function(event) { console.log('my link click'); $('#mylink2').click(); }); $('#mylink2').on('click', function(event) { console.log('my link2 click'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myelement"> <div class="container"> <div class="testitem"> <a id="mylink" href="#"> Test Link 1 </a> </div> </div> <div class="container"> <a id="mylink2" href="#"> Test Link 2 </a> </div> </div> 

Try this:

    $('#mylink, #mylink2').on('click', function(event){
        console.log($("#mylink1").text());
        console.log($("#mylink2").text());
    });

It should be straightforward since you are using unique IDs for the two elements. Triggering the second elements click event in the first elements handler.

     $("#mylink").on("click", function(){
      $("#mylink2").trigger("click");
     });`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM