将输入字符串附加到锚标记 href
Append input string to anchor tag href
尝试使用 vanilla js 将用户输入的字符串附加到锚标记 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>
但是,这不起作用
你应该在函数外部而不是内部执行函数
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
希望这就是您想要的。
function searchProduct(){
var inputValue = document.getElementById('inputId').value;
document.getElementById('go').href = "mywebsite/product/"+inputValue;
}
<input id="inputId" type="text">
<a id="go" onclick="searchProduct();" href="">anchor tag</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()
});
})();
尝试使用 vanilla js 将用户输入的字符串附加到锚标记 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>
但是,这不起作用
你应该在函数外部而不是内部执行函数
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
希望这就是您想要的。
function searchProduct(){
var inputValue = document.getElementById('inputId').value;
document.getElementById('go').href = "mywebsite/product/"+inputValue;
}
<input id="inputId" type="text">
<a id="go" onclick="searchProduct();" href="">anchor tag</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()
});
})();