Javascript image src attribute returns wrong value

2019-07-19 15:19发布

I have a little javascript code attached to a button with onclick to the following code:

function ondelete () {

    var getDiv = document.getElementById("imgdiv");
    var lb_img = $("#imgdiv").children();
    for (var i = 0; i < lb_img.length; i++) {
        console.log(lb_img[i].src);
    }
}

This returns a single output which is great, this is the corresponding html when opened in chrome with F12 developers tool:

<div id="imgdiv" class="modal-body next">
    <img draggable="false"src="http://(urlfrommywebsite)/A_LANX/get/OTc1/179f42">
</div>

So the code should return that src attribute, but instead it returns

http://127.0.0.1/stage/local/admin/galleries/gallery/2

which is my url. On other images it returns the value of another img or this same url, really weird. This all happens inside a lightbox, so the normal code without a lightbox open is

<div id="imgdiv" class="modal-body next"></div>

I'm really stuck here, so a little help is really usefull :)

EDIT:

No answer seems to help so far, any recommendations for other lightboxes with maybe a function like getImage() or something simular?

p.s. fancybox doesn't quitte work for me either.

3条回答
萌系小妹纸
2楼-- · 2019-07-19 15:43

you can try this:

function ondelete() {

        var lb_img = $("#imgdiv").children();
        for (var i = 0; i < lb_img.length; i++) {
            console.log(lb_img[i].getAttribute("src"));
        }
    }

for more info about attr() and getAttribute() see this post:Difference between jQuery's attr() and getAttribute()

查看更多
何必那么认真
3楼-- · 2019-07-19 15:47

Use jQuery's attr() to get attributes

$("img").attr("src");

Edit the selector accordingly

http://jsfiddle.net/b3xdgn83/1

查看更多
祖国的老花朵
4楼-- · 2019-07-19 15:55

You are using this code to get the image url.

<div id="imgdiv" class="modal-body next">
<img draggable="false" src="http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg">

jQuery Code :

$( document ).ready(function() {
alert($('#imgdiv img').attr('src'));

});

Live Demo

查看更多
登录 后发表回答