这是我的代码:
<script type="text/javascript" language="javascript">
var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);
</script>
<img src="https://yt3.ggpht.com/-xf7anhq4eRo/AAAAAAAAAAI/AAAAAAAAAAA/wQIFalodFjE/s88-c-k-no/photo.jpg" id="youtubeimg">
Jsfiddle:http://jsfiddle.net/vrnsydLb/
我必须在img之前放置脚本代码,但它不起作用。我尝试了onload,它工作但所有内容都在页面中删除了。有什么办法吗?
答案 0 :(得分:1)
更改以下内容:
<html>
<head>
<script>
function toRun() {
var src = document.getElementById('bar').getAttribute('src');
document.getElementById('foo').textContent = src;
}
window.onload = toRun;
</script>
</head>
<body>
<img src="https://yt3.ggpht.com/-xf7anhq4eRo/AAAAAAAAAAI/AAAAAAAAAAA/wQIFalodFjE/s88-c-k-no/photo.jpg" id="bar">
<div id="foo"></div> ##must be closed##
</body>
</html>
答案 1 :(得分:0)
<html>
<head>
<script>
function toRun() {
var src = document.getElementById('bar').getAttribute('src'),
text = document.createTextNode(src),
container = document.getElementById("mesaj1");
container.insertBefore(text, container.childNodes[0]);
}
window.onload = toRun;
</script>
</head>
<body>
<div id="mesaj1"><img src="https://yt3.ggpht.com/-xf7anhq4eRo/AAAAAAAAAAI/AAAAAAAAAAA/wQIFalodFjE/s88-c-k-no/photo.jpg" id="bar"></div>
</body>
</html>
我还建议使用css隐藏“mesaj1”div,然后在toRun()函数的末尾显示它,以防止图像在调用onload之前没有文本显示。