简体   繁体   中英

How do I get img src?

I'm not sure why, but I'm having trouble getting image src value? Here's my HTML:

<div id="gallery">
 <img src="css/images/cat.jpg" id="main-img">
</div>

Here's my javascript:

window.setInterval(function() {
    var currentImage = $("#main-img").attr("src");
    window.alert(currentImage);
}, 5000);

But I keep getting undefined whenever the alert comes up.

Just as a footnote as much as anything else.

For this jQuery :

setInterval(function() {
    var currentImage = $("#main-img").attr("src");
    window.alert(currentImage);
}, 5000);

the equivalent in vanilla javascript is:

setInterval(function(){
    var currentImage = document.querySelector('#main-img').getAttribute('src');
    window.alert(currentImage);
}, 5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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