简体   繁体   中英

Simulate click on one element with JS or Jquery when clicking a different element

I want one item to be clicked when I click on a different one, but I keep seeing these complicated answers that, frankly, don't make any sense. I feel like it should be easy as this, but this doesn't work.

<div class="myElement" onclick="myFunction()"></div>
<a href="https://example.com" class="myElement2"></a>
function myFunction() {
  document.getElementsByClassName('myElement2').click();
}

There're some points you need to know:

  1. getElementsByClassName returns an array
  2. there have to be something in the <div> , otherwise it's height is 0px, so you have no where to click

try this one:

 <script> function myFunction() { for (let e of document.getElementsByClassName('myElement2')) { e.click(); } } </script> <div class="myElement" onclick="myFunction()"> hello </div> <a href="https://example.com" class="myElement2"></a>

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