gpt4 book ai didi

javascript - 使用 HTML 搜索栏输入调用 javascript 函数

转载 作者:行者123 更新时间:2023-12-03 11:36:19 26 4
gpt4 key购买 nike

所以我有一个导航栏表单,我基本上希望有人输入 3 位数字或 5 位数字,所以我尝试使用搜索栏输入中的内容并使用该数字调用该函数,并且根据情况打开某个链接。但我无法让它工作,我在调用我的函数时遇到了问题,然后由于单击了按钮,它打开了相应的链接。如果有任何帮助,我将不胜感激。

HTML:

<form class="navbar-form" style="width: 200px">
<div class="input-group">
<input type="text"
class="form-control"
id="submit"/>
<button class="input-group-addon">
<i class="fa fa-search"
style="color: #fff"
onclick="searchButton()">
</i>
</button>
</div>
</form>

Javascript:

var input = document.getElementById('submit');

function searchButton() {
var str;
if (input.length == 3) {
str = '#/root/home/three/' + input.value;
<a href="str"></a>
}
else if (input.length == 5) {
str = '#/root/home/five/' + input.value;
<a href="str"></a>
}
else{
alert('Invalid input');
}
};

http://jsfiddle.net/BootstrapOrBust/wg1s25bq/3/

最佳答案

使用

location.href = "url adress that you want to open";

而不是写html链接标签

<a href="str"></a>

进入JavaScript代码

您可以使用

获取网页的当前 url
document.URL

您可以通过将搜索输入附加到当前 url 字符串来生成 url 字符串,除此之外,如果您想加载新页面,则附加的 url 字符串不应以井号字符 (#) 开头

var input = document.getElementById('submit');

var currentUrl = document.URL;

function searchButton() {
var str;
if (input.value.length == 3) {
str = 'root/home/three/' + input.value;
location.href = currentUrl + str;
}
else if (input.value.length == 5) {
str = 'root/home/five/' + input.value;
location.href = currentUrl + str;
}
else{
alert('Invalid input');
}
};

关于javascript - 使用 HTML 搜索栏输入调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26494855/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com