【问题标题】:Append input string to anchor tag href将输入字符串附加到锚标记href
【发布时间】:2015-02-10 06:24:05
【问题描述】:

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

但是,这不起作用

【问题讨论】:

  • 在哪里触发函数?
  • 请显示锚标签的html
  • 好的——还有输入元素。
  • 您在页面加载时触发了searchProduct(),之前有人在inputId 框中填写任何内容。你需要触发它,在按钮点击、onblur 或某事上

标签: javascript anchor href


【解决方案1】:

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

this jsBin

【讨论】:

  • 这与我的建议类似。非常直接。
  • 这是一个很好的解决方案,addEventListener 函数可以将e.target.value 作为参数传递给searchProduct 函数,并且可以避免getElementById('inputId').value;
  • 没有得到想要的结果
【解决方案2】:

我希望这是你想要的。

  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>
	

【讨论】:

  • 有a为什么还有按钮
  • 锚标签是打开一个链接。还有一个按钮是改变锚标签的href。
  • 不需要这一步,从你的答案中删除按钮,将 onclick 放在锚点上,我会接受它。它有效,谢谢
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-05
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多