所以我想编写一个js代码来创建一个图像标签......就像这样
var oImg=document.createElement("img");
oImg.setAttribute('src', 'www.site.com/banner/a.gif');
oImg.setAttribute('alt', 'na');
document.body.appendChild(oImg);
所以这就是问题......现在它只是将图像附加到身体上 但我希望它能准确显示我放置此代码的位置...例如,如果我把它放在侧边栏中,我希望该图像显示在侧栏中
我不想在页面上添加任何额外的html标签,只需要这个js代码
可能吗?
答案 0 :(得分:0)
您可以按ID
替换当前脚本标记<script id='image_replace'>
var oImg=document.createElement("img");
oImg.setAttribute('src', 'http://placehold.it/350x150');
oImg.setAttribute('alt', 'na');
var this_script = document.getElementById('image_replace');
this_script.parentElement.replaceChild(oImg,this_script);
</script>
答案 1 :(得分:0)
你写的代码将img附加到正文中,因为它说:&#34; document.BODY.appendChild(yourElementToAppend)&#34;。当然它会将元素附加到身体上。
为了回答你的问题,你的推理是不正确的。 解决问题的最好方法是给侧边栏(或者你需要的子元素)提供一个id(或类),而在.js中,你可以轻松地使用jQuery并编写你输入的相同代码。问题除了最后一行,应该替换为: $(&#34; .nameIdYouWroteInTheSidebar&#34)的appendChild(oImg);
希望这可能有用:)