[英]Dynamicaly changing HREF attribute in <A> tag
我正在網站上工作。 該代碼應該具有很高的可移植性,並且可以在不同的平台上運行。 我需要在<a>
標記中動態更改HREF屬性。
我的代碼如下所示:
function getValue(element) { var theValue = prompt('Please enter the value for the link: ' + element.getAttribute('HREF'), '0'); if (theValue == null) { return false; } var newLink = element.getAttribute('HREF') + ' ' + theValue; element.setAttribute('HREF', newLink); // test what I set: prompt(newLink); return true; }
<A HREF="https://www.w3schools.com" ONCLICK="return getValue(this)">click here</A>
如果訪問者單擊我網站上的“單擊我”鏈接,將顯示一個提示窗口。 如果用戶輸入希望的值,則將打開帶有URL的網站: https://www.w3schools.com theValue
必須打開“值”。
現在,什么都沒有發生。 非常感謝!
我需要澄清幾個想法。 這個例子非常簡化。 我的網站正在從引擎導出鏈接以供內部使用。 偽造鏈接沒有安全性問題。 該網站由1.000個鏈接組成,網址為www.w3schools.com。 無法為<a>
標簽添加一些靜態ID。 無法創建某些表格。 對於具有匹配的編輯框和要發布的按鈕的鏈接,這不是一個好的解決方案。
最好的解決方案可能是單擊鏈接,在提示窗口中輸入值,然后如上所述重定向URL。 感謝吉爾的審查。 現在,我看到該代碼可在IE中運行,但無法在Mozilla瀏覽器中運行。
如果您只想重定向到新的URL,則無需更改元素的href,只需調用window.open(newLink)
,它將打開帶有指定鏈接的新選項卡。 如果要在同一頁面上重定向,請使用window.location.href = newLink
。
請注意,您使用var newLink = element.getAttribute('HREF') + ' ' + theValue;
創建了無效的URL var newLink = element.getAttribute('HREF') + ' ' + theValue;
您要在參數中添加一個空格,則需要一個/
。
function getValue(element) { var theValue = prompt('Please enter the value for the link: ' + element.getAttribute('href'), '0'); if (theValue == null) { return false; } var newLink = element.getAttribute('href') + '/' + theValue; window.open(newLink); return true; }
<a href="https://www.w3schools.com" onclick="return getValue(this)">click here</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.