简体   繁体   中英

JQuery get img src and use it in a as data attribute

I'm trying to use a javascript library which requires a specific HTML structure but unfortunately I am not allowed to change it.
The structure comes from a template and I have to work with what I have.
The point is that I try to copy every image's src and put it in as data-largesrc="image/source/here".
Any clue how I could do this? I have this until now but it's not working as intended:

$(document).ready(function () {
    $("a").attr('data-largesrc', "'" + $("a").children().attr('src')) + "'");
});

And the HTML structure is like this:

<div class="container">
    <div id="products" class="productsList main">
        <ul id="og-grid" class="list og-grid">
            <li class="l1 i1 column1">
                <a href="?17,barracuda-email-security-gateway" tabindex="-1">
                    <img src="files/150/BARRACUDAESG.jpg.png" alt="BARRACUDAESG.jpg.png">
                </a>
            </li>
        </ul>
    </div>
</div>

I'm sure this should be solved rather easy but I can't seem to find a solution. Thank you very much if you can help me!

Try it

$(document).ready(function () {
  $.each($("a"), function(i, k){
    $(this).data("largesrc", $(this).find("img").attr("src"));
  });
});

The children() method returns all direct children of a parent element. In other words, it will return an array. What you are looking for is a single object.

Anyways, it would be best to use the data() function instead

 function getImageSource() { var imgSrc = $("img").first().prop("src"); $("img").data("largesrc", imgSrc); var data = $("img").data("largesrc"); $("#img-data-value").html(data); } $("button").on("click", getImageSource); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div id="products" class="productsList main"> <ul id="og-grid" class="list og-grid"> <li class="l1 i1 column1"> <a href="?17,barracuda-email-security-gateway" tabindex="-1"> <img src="files/150/BARRACUDAESG.jpg.png" alt="BARRACUDAESG.jpg.png"> </a> </li> </ul> </div> </div> <button>Get Image Source</button> <p id="img-data-value"></p> 

First of all, you do not need the extra quotation marks. Second, you should use .first() instead of .children() because .children() will return an array whereas .first() will return the first child (and yours only has one child).

    $(document).ready(function () {
        $("a").data('largesrc', $("a").first().attr('src')));
    });

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