我对网络开发有些陌生,所以我一直在努力学习。我有一个 500 x 500 的 div。在那个 div 里面我有两个 div,每个都是 250x500。所以我的外部 div 被两个内部 div 填满了。
我对其进行了设置,以便当我单击第一个 div(左侧)时调用 JavaScript,并且提示弹出框要求提供网站 URL,然后将其存储在字符串变量中。
我怎样才能让第二个 div(右边的那个)从左边的 div 的警告框中获取字符串变量并将其放入 href 标签中,这样我就可以从右边的 div 链接到网站?
a href 标签能否接受来自变量的值作为其链接?也许我做错了,有没有更好的方法来解决这个问题?感谢您的帮助!
最佳答案
有DOM创建方法:
// Create an element
var aEl = document.createElement("a");
// Ask the user for the URL
aEl.href = prompt("Please enter the website URL");
// Determine whether to use innerText or textContent
if ("innerText" in aEl)
aEl.innerText = aEl.href;
else
aEl.textContent = aEl.href;
// Add the link to the right div
document.getElementById("rightDiv").appendChild(a);
或者直接的 innerHTML 方法:
var url = prompt("Please enter the website URL");
document.getElementById('rightDiv').innerHTML = '<a href="'+url+'">'+url+'</a>';
关于javascript - 我可以将字符串变量传递到网站链接的 <a href> 标记中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2694643/