如何使用 javascript 函数更改 href?

问题描述 投票:0回答:2

我有一个按钮,当用户点击它时,页面将被重定向到另一个链接。

Index.html:

<input
  type="text"
  placeholder="Search"
  id="input-box"
  autocomplete="off"
  style="width: 250px;">
<button id="submitbtn"
        onClick="submitClicked"
        href="">
</button>
</input>

Script.js:

document.getElementById("submitbtn").onclick = function() {submitBtn()};

  function submitBtn() {
    for(let i=0; i<availableKeywords.length; i++){
      if (result == availableKeywords[i]){ //checks if the result(inputted by the user) is matched with the keyword
        document.getElementById("submitbtn").href = "/index2.html?key=${availableKey[i]}" //How do i make this work?
      }
    }
  }
javascript html function href
2个回答
1
投票

button
本身没有
href
属性,但您可以将其设置为属性。

document.getElementById("submitbtn").setAttribute("href", `/index2.html?key=${availableKey[i]}`);

我可能应该指出,这不会自动重定向。

要进行重定向,您可以使用

window.location.href
代替。

用这个替换你的按钮更新代码。

window.location.href = `/index2.html?key=${availableKey[i]}`

0
投票

评论

  1. Html 输入标签没有结束标签。
  2. 如果在 html 中有 onclick,则不必在 javascript 中设置 onclick。

HTML

<input id="input-box" type="text" placeholder="Search" autocomplete="off" style="width: 250px;">
<button id="submit-btn" onclick="submitClicked(this)">Submit</button>

JS

const availableKeywords = [];

function submitClicked() {
  const input = document.getElementById('input-box');
  const value = input.value ?? null;

  for (const keyword of availableKeywords || []) {
    if ( value != keyword ) continue;
    location.href = `${location.origin}/index2.html?key=${keyword}`;
    break;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.