链接在 javascript 创建的映像中



我正在尝试为我的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>`

谁能帮我?提前致谢

不要使用document.write().创建一个新的元素,就像创建图像一样,并将图像追加到定位点元素,并将锚点元素追加到包装器。

//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">");,因为如果您在用双引号定义的字符串中使用双引号,则需要转义双引号。

最新更新