我正在尝试生成到我的javascript生成图像的链接。
<div id="wrapper"></div>
<script type="text/javascript">
var divWrapper = document.getElementById('wrapper');
var image = document.createElement('img');
image.src = 'image.png';
image.height = 100;
image.width = 50;
image.style.position = "absolute";
image.style.left = 60 + "px";
image.style.top = 32 + "px";
document.write("<a href="index.php">); //HERE MIGHT BE THE MISTAKE
divWrapper.appendChild(image);
</script>`
有人可以帮我吗?预先感谢
答案 0 :(得分:1)
请勿使用document.write()
。像创建图像一样创建一个新元素,然后将图像附加到anchor元素,并将anchor元素附加到包装器。
//define elements
var divWrapper = document.getElementById('wrapper');
var image = document.createElement('img');
var a = document.createElement('a');
//set image attributes
image.src = 'image.png';
image.height = 100;
image.width = 50;
image.style.position = "absolute";
image.style.left = 60 + "px";
image.style.top = 32 + "px";
//set anchor attributes
a.href = "index.php";
//Append the elements
a.appendChild(image);
divWrapper.appendChild(a);
<div id="wrapper"></div>
document.write("<a href="index.php">);
中的引号也是错误的,应该是document.write("<a href=\"index.php\">");
,因为如果在带双引号的字符串中使用双引号,则需要转义双引号。