繁体   English   中英

如何使用jQuery获取和设置图片

[英]How to get and set image using jQuery

这是我的jFiddle: http : //jsfiddle.net/MEHhs/41/

这部分不起作用

//get the URL from image
        var imgUrl = document.getElementById("img").src;

错误消息未捕获的TypeError:无法读取属性'src'为null

经过研究,我找不到更好的方法。 有人可以帮忙吗? 感谢!

picture ID是picture而不是img

采用

var imgUrl = document.getElementById("picture").src;      

演示无错误

当您使用jQuery时,

$('#picture').click(function () {
    var picture = $('#picture');
    //get the URL from image
    var imgUrl = picture.prop('src');
    //if image 1 is displayed, change to image 2
    if (imgUrl == "http://www.mathe-fuer-antimathematiker.de/images/vorderseite.png") {
        picture.prop('src', 'http://www.mathe-fuer-antimathematiker.de/images/rueckseite.png');
    }
    //if image 2 is displayed, change to image 1
    else {
        picture.prop('src', 'http://www.mathe-fuer-antimathematiker.de/images/vorderseite.png');
    }
});

DEMO

此外,使用.prop()获取匹配元素集中第一个元素的属性值,或者为每个匹配元素设置一个或多个属性。

在jQuery中使用“ attr”属性。

img的idpicture .use:

var imgUrl = document.getElementById("picture").src;    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM