将输入字符串附加到锚点标记href
尝试使用vanilla js将用户输入的字符串追加到锚点标记href。将输入字符串附加到锚点标记href
<script>
function searchProduct(){
var inputId = document.getElementById('inputId').value;
document.getElementById('go').href = "mywebsite/product/" + inputId;
}
searchProduct();
</script>
<a id="go"><p>Go</p></a>
然而,这是不正常
你触发searchProduct()
一次加载页面时。您需要在ID inputId
的输入更新后触发 - 无论是通过按下按钮还是当他们离开文本框时,或者其他东西。
这里是一个触发searchProduct()
功能相关的例子,当他们离开文本框:
(function() {
function searchProduct(){
var inputId = document.getElementById('inputId').value;
document.getElementById('go').href = "mywebsite/product/" + inputId;
}
document.getElementById('inputId').addEventListener('blur', function() {
searchProduct()
});
})();
这与我所建议的类似。非常直截了当。 – williamdnapier 2015-02-09 21:03:41
这是一个很好的解决方案,'addEventListener'函数可以将'e.target.value'作为参数传递给'searchProduct'函数,'getElementById('inputId')。value;'可以避免。 – Deepak 2015-02-09 21:07:22
没有得到想要的结果 – softcode 2015-02-09 21:18:32
你应该执行的函数本身之外,内部没有
function searchProduct(){
var inputId = document.getElementById('inputId').val();
document.getElementById('go').href = "mywebsite/product/" + inputId;
}
searchProduct(); // This should be executed via an eventListener to the input
,这是一个错别字,不过这不是问题,编辑问题 – softcode 2015-02-09 20:49:16
我希望这是你想要的。
function searchProduct(){
var inputValue = document.getElementById('inputId').value;
document.getElementById('go').href = "mywebsite/product/"+inputValue;
}
\t <input id="inputId" type="text">
\t <a id="go" onclick="searchProduct();" href="">anchor tag</a>
\t
你在哪里触发功能? – 2015-02-09 20:43:40
请显示锚标记的html – fnostro 2015-02-09 20:43:44
@fnostro编辑 – softcode 2015-02-09 20:46:02