[英]Javascript dynamic link issues?
可能有重復的內容(我嘗試過檢查有關創建動態鏈接的問題,但它們引用的是靜態鏈接-我希望對用戶隱藏此鏈接)。 在ww3網站上測試以下代碼時:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
document.write("<a href="www.google.com">Google</a>");
</script>
</body>
</html>
我得到:
http://www.w3schools.com/jsref/%22www.google.com%22
作為鏈接地址,而不是www.google.com。
我該如何解決這個問題? 以及如何使鏈接僅在設置的時間后出現? 請注意,這是代碼的簡化版本,以提高可讀性(動態鏈接將包括在運行腳本時分配的兩個浮點變量)。
<a>
標記的href
必須包含協議http://
,否則它鏈接到相對於鏈接所在頁面的文檔:
// Print quote literals, not html entities `"`
document.write("<a href='http://www.google.com'>Google</a>");
document.write()
的用例通常是有限的,因為在頁面加載后不能覆蓋整個內容而不能使用它。 很多時候,您需要在頁面呈現后創建元素。 在這種情況下,您將使用document.createElement()
和appendChild()
。
// Create the node...
var newlink = document.createElement('a');
newlink.href = 'http://www.google.com';
// Set the link's text:
newlink.innerText = "Google";
// And add it to the appropriate place in the DOM
// This just sticks it onto the <body>
// You might, for example, instead select a specific <span> or <div>
// by its id with document.getElementById()
document.body.appendChild(newlink);
順便說一下,w3schools不隸屬於W3C ,並且通常不建議使用它們的示例,因為它們經常過時或不完整。
您有2個問題:
1)您需要在URL之前添加http://
,以便它是: http : //www.google.com 2)您不需要在document.write中使用引號,但是如果您願意,可以使用以下三種方法之一:
document.write('<a href="http://www.google.com">Google</a>');
document.write("<a href='http://www.google.com'>Google</a>");
document.write("<a href=http://www.google.com>Google</a>");
使用斜杠“ \\”轉義引號
要使鏈接絕對,請在URL的開頭包含“ http://”。 寫出:
<a href="http://www.google.com">
代替
<a href="www.google.com">
第二個示例將被視為相對網址,例如index.html
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.