我想用一个类替换图像到一个div里面有文本,我怎么能做到这一点?
<script>
$('img.vCSS_img_history_off').replaceWith('<div id="button">Turn History Off</div>');
</script>
我知道代码搞砸了,但这只是为了描绘我正在寻找的画面,有什么建议吗?
在搜索DOM中的元素之前,您需要确保DOM准备就绪:
$(document).ready(function(){
$('img.vCSS_img_history_off').replaceWith('<div id="button">Turn History Off</div>');
});
或者,您可以在图像后面添加任何您需要的内容,然后将其删除:
$(document).ready(function(){
$("img").after("<div>Inserted div</div>").remove();
});
的例子。
这里是.after()
的详细介绍,这里是.remove()
的详细介绍
另一种选择是使用这个,但它会擦除其他父级的子级(如@Vide Simas所说):
$(".myImage").parent().html('<div>hello</div>');
你写的东西看起来很好,我用replaceWidth
写了一个jsfiddle: http://jsfiddle.net/ydZg5/
错误一定在别处
下面的代码将用包含文本"This is mydiv text"的div替换类名为"myImageClassName"的图像:
$('img.myImageClassName').replaceWith('<div>This is my div text</div>');
但是,是的,我同意其他人的观点…你的代码看起来很好