用javascript替换图片

问题描述:

我想用javascript替换gif文件.我发现下面的方法.有什么办法可以将javascript标记放在img标记之前?

I want to replace the gif file by javascript. I find the method below. Is there any way i can place the javascript tag before the img tag?

<img class="myImg" src="compman.gif" width="107" height="98">

<script>
    document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
</script>

在文档就绪"之前,无法安全地操纵页面.使用jquery的$(document).ready(),它将等待直到页面被加载并准备好进行操作之后再执行(无论它在页面上的什么位置).示例:

A page can't be manipulated safely until the document is "ready." Using jquery's $(document).ready(), it Will wait until the page is loaded and ready to be manipulated before executing (no matter where it is on the page). Example:

<script>
    $(document).ready(function() {
        document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
    });
</script>
<img class="myImg" src="compman.gif" width="107" height="98">

然后,您还可以在jquery中利用选择器(例如,$(".class")其中class是您的类,或者$("#id")其中id是id),并将代码更改为:

You could also then leverage selectors inside jquery (e.g. $(".class") where class is your class, or $("#id") where id is the id) and change the code to:

<script>
    $(document).ready(function() {
        $(".myImg").attr('src',"hackanm.gif");
    });
</script>
<img class="myImg" src="compman.gif" width="107" height="98">

如果您以后还要在javascript中进行更改,甚至可以将其存储在变量中!

And further you could even store it in a variable if you wanted to change it later on in javascript as well!

<script>
    $(document).ready(function() {
        var myImg = $(".myImg");
        var newImg = "hackanm.gif";
        myImg.attr('src', newImg);
    });
</script>
<img class="myImg" src="compman.gif" width="107" height="98">

希望这可以帮助您学习javascript内的一些新技巧!编码愉快!

Hope this helps you learn a few new tricks inside javascript! Happy coding!

更多信息