2015-02-09 114 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