2015-02-09 115 views
-1

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

然而,这是不正常

+1

你在哪里触发功能? – 2015-02-09 20:43:40

+0

请显示锚标记的html – fnostro 2015-02-09 20:43:44

+0

@fnostro编辑 – softcode 2015-02-09 20:46:02

回答

3

你触发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

+0

这与我所建议的类似。非常直截了当。 – williamdnapier 2015-02-09 21:03:41

+0

这是一个很好的解决方案,'addEventListener'函数可以将'e.target.value'作为参数传递给'searchProduct'函数,'getElementById('inputId')。value;'可以避免。 – Deepak 2015-02-09 21:07:22

+0

没有得到想要的结果 – softcode 2015-02-09 21:18:32

0

你应该执行的函数本身之外,内部没有

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 
+0

,这是一个错别字,不过这不是问题,编辑问题 – softcode 2015-02-09 20:49:16

0

我希望这是你想要的。

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

+0

为什么有一个按钮,如果有一个 – softcode 2015-02-09 20:50:22

+0

Anchor标记是打开一个链接。而一个按钮就是改变锚标签的href。 – roshan 2015-02-09 20:52:48

+0

没有必要这一步,从你的答案删除按钮,把onclick锚,我会接受它。它的工作原理,谢谢 – softcode 2015-02-09 20:54:39