将输入字符串附加到锚标记href

Append input string to anchor tag href

本文关键字:href 输入 字符串      更新时间:2023-09-26

尝试使用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>

但是,不起作用

加载页面时,您触发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()
  });
})();

请参阅此jsBin

我希望这就是你想要的。

  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>
	

您应该在自身之外执行函数,而不是在内部

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