Onclick Javascript 函数添加图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10284238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Onclick Javascript Function to adding image
提问by Bai Lor
I am trying to add a function that when a customer click on the small thumbnail, it adds an image. see code below.
我正在尝试添加一个功能,当客户单击小缩略图时,它会添加一个图像。请参阅下面的代码。
<html>
<head>
<script type="text/javascript">
<!--
function addimage2() {
var img = document.createElement("img");
img.src = "swatch.jpg";
img.height = 75;
img.width = 113;
img.style.top=800;
img.style.right=100;
document.body.appendChild(img);
}
//-->
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="43%" rowspan="2"><img src="tuffet-diagram.jpg" width="270" height="326"></td>
<td width="57%" height="162">Zone 1:</td>
</tr>
<tr>
<td>Zone 2: </td>
</tr>
<tr>
<td colspan="2">Zone 1 color:
<img src="swatch-sm.jpg" alt="swatch-sm" onClick="addimage2();"></td>
</tr>
<tr>
<td colspan="2">Zone 2 color:</td>
</tr>
</table>
</body>
</html>
it keeps adding next to the thumbnail and not where the specify location such as when a customer click on Zone1 swatch, it should add to the Zone 1 area, etc.
它不断添加到缩略图旁边,而不是指定位置的位置,例如当客户单击 Zone1 色板时,它应该添加到 Zone 1 区域等。
here's the link to my page: http://www.manufacturingsolutionscenter.org/salma/tuffet-color.html
这是我页面的链接:http: //www.manufacturingsolutionscenter.org/salma/tuffet-color.html
Thank you.
谢谢你。
回答by Surreal Dreams
The script is doing exactly what you're instructing it to do - appending the new image to the body of the document: document.body.appendChild(img);
该脚本完全按照您的指示执行操作 - 将新图像附加到文档正文中: document.body.appendChild(img);
This literally means, "append this new element as a child of the body tag." That places the new tag just before </body>
. If you want to add the new image elsewhere, target the precise location you want it added.
这字面意思是“将这个新元素附加为 body 标签的子元素”。这会将新标签放在</body>
. 如果您想在别处添加新图像,请定位您想要添加的精确位置。
回答by John Fisher
This code:
这段代码:
document.body.appendChild(img)
determines where the image goes. You'll need to figure out which element should get the image appended to it and place it there instead.
确定图像的去向。您需要确定应该将图像附加到哪个元素并将其放置在那里。
BTW, this type of document manipulation is immensely easierif you use JQuery.
顺便说一句,如果您使用 JQuery ,这种类型的文档操作会非常容易。
回答by Denys Séguret
Try this :
试试这个 :
function addimage2(where) {
var img = document.createElement("img");
img.src = "swatch.jpg";
img.height = 75;
img.width = 113;
img.style.top=800;
img.style.right=100;
where.parentNode.appendChild(img);
}
and
和
<img src="swatch-sm.jpg" alt="swatch-sm" onClick="addimage2(this);">
The idea is to provide the location where the new image must be added in the function call.
这个想法是提供必须在函数调用中添加新图像的位置。