简体   繁体   中英

clicking link based on input value

Hello I was wondering is there a way for me to click a link with button but i want to click the link based on an input value?

Sorry for bad English

 function clicklink() { document.getElementsByClassName("hud-link")[0].click(); } 
 <div class="hud"> <a class="hud-link" href="https://stackoverflow.com">Link Here 1</a> </div> <br> <div class="hud"> <a class="hud-link" href="https://google.com">Link Here 2</a> </div> <br> <div class="hud"> <a class="hud-link" href="https://yahoo.com">Link Here 3</a> </div> <br> <div class="hud"> <a class="hud-link" href="https://bing.com">Link Here 4</a> </div> <br> <input type="number" min="0" max="4" value="0"> <button onclick="clicklink();">Click Link</button> 

You'll want to first get both the button and the input elements as variables. Then you'll want to use the .value of your input as the index in your .getElementsByClassName() selector.

Also, you'll want to make use of Unobtrusive JavaScript by adding an event listener to your button, through which you call your function.

This can be seen in the following:

 const button = document.getElementsByTagName('button')[0]; const input = document.getElementsByTagName('input')[0]; button.addEventListener('click', function() { document.getElementsByClassName("hud-link")[input.value].click(); }); 
 <div class="hud"> <a class="hud-link" href="https://stackoverflow.com">Link Here 1</a> </div> <br> <div class="hud"> <a class="hud-link" href="https://google.com">Link Here 2</a> </div> <br> <div class="hud"> <a class="hud-link" href="https://yahoo.com">Link Here 3</a> </div> <br> <div class="hud"> <a class="hud-link" href="https://bing.com">Link Here 4</a> </div> <br> <input type="number" min="0" max="4" value="0"> <button>Click Link</button> 

You can try this code:

function clicklink() {
var number = document.getElementsByTagName("input")[0].value;
  document.getElementsByClassName("hud-link")[number].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