[英]Can't go to a url in javascript
我完全不喜歡Web編程(剛剛開始)。 我知道C,C ++和x86-assenbly(一點點)。 我想為瀏覽器創建自己的主頁。 在大多數情況下,這是非常基本的html,但我想在頂部找到一個搜索欄,將其重定向到具有相關結果的duckduckgo,這就是問題所在。 我正在嘗試的代碼:
<form>
<input type="text" id="query"/>
<button id="button" class="button" onclick="openInDuck()">Search</button>
</form>
<script>
function openInDuck(){
var x= "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location = x;
}
</script>
是的,我忘記了,如果那很重要,我會在archlinux上使用qutebrowser。 提前致謝。
您在重定向中缺少.href
。 同樣,您應該將按鈕類型更改為button
而不是默認值。
function openInDuck() { var x = "https://duckduckgo.com/?q="; x += document.getElementById("query").value; window.location.href = x; }
<form> <input type="text" id="query" /> <button id="button" class="button" onclick="openInDuck()" type="button">Search</button> </form>
請注意,如果您只需要通過其他api進行搜索,則重定向用戶不是理想的選擇。
您可以使用以下
function openInDuck() {
var x="https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.open(x);
}
問題是單擊該按鈕時提交了您的表單,就像這樣:)
<input type="text" id="query" />
<button id="button" class="button" onclick="openInDuck()">Search</button>
<script>
function openInDuck() {
var x = "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location = x;
}
</script>
您已接近解決方案。 在JS代碼中,必須在window.location
之后添加.href
才能為當前窗口設置新的href(URL)。 在HTML代碼中,建議您使用onsubmit
屬性發送input type="submit"
的表單:
function openInDuck() { var x = "https://duckduckgo.com/?q="; x += document.getElementById('query').value; window.location.href = x; return false; // Prevent the form submission }
<form onsubmit="return openInDuck()"> <input type="text" id="query"> <input type="submit" id="button" class="button" value="Search"> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.