我有一个按钮,当用户点击它时,页面将被重定向到另一个链接。
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?
}
}
}
button
本身没有href
属性,但您可以将其设置为属性。
document.getElementById("submitbtn").setAttribute("href", `/index2.html?key=${availableKey[i]}`);
我可能应该指出,这不会自动重定向。
要进行重定向,您可以使用
window.location.href
代替。
用这个替换你的按钮更新代码。
window.location.href = `/index2.html?key=${availableKey[i]}`
评论
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;
}
}