简体   繁体   中英

jQuery : How To Get src Value of Multiple img

I have this PHP script to generate thumbnails of a directory. number of files inside that directory are dynamic :

<?
    if (isset ($product_imgfiles)) {
        echo '<div class="row">';

        for ($i=2; $i<($num_product_imgfiles+2); $i++) {
            echo '<div class="col-xs-4 col-md-2" style="padding-left: 7px; padding-right: 7px;">
                    <a href="#" class="thumbnail product_imgfiles">
                        <img src="'. $directory . $product_imgfiles[$i] .'" style="margin-bottom: 5px;">
                        <span><i class="fa fa-times-circle"></i> hapus</span>
                    </a>
                </div>';
        }

        echo '</div>';
    }
?>

and I also have this jquery to listen the event each time the thumbnail is clicked :

echo '
$( ".product_imgfiles" ).each( function(index)  {
    $( ".product_imgfiles" ).click(function() {
        event.preventDefault();
        var img_files = $( ".product_imgfiles img" ).attr( "src" );
        alert( img_files );
        alert( \''.$product_token.'\' );
        alert( '.$secret_token.' );
    });
}); 

';

the jquery part is able to show alert message. but, unfortunately, the loop won't stop until number of product_imgfiles and it shows same src value of img tag.

while what I need is to get src value of img tag once the class product_imgfiles is clicked. how to get each src value of each img class when it's clicked? thank you.

Remove the .each loop.

.click() inherently applies it to each element already, you don't need to loop over them again.

echo '
    $( ".product_imgfiles" ).click(function(event) {
        event.preventDefault();
        var img_files = $( this ).children('img').attr( "src" );
        alert( img_files );
        alert( \''.$product_token.'\' );
        alert( '.$secret_token.' );
    });
';

Additionally, you need to actually pass the event variable into the constructor. As was brought out in the comments, you reference the current object being clicked with this instead of using the selector again.

Also, that confusing bit with the product token and secret token is a little strange. It's going to be the same for every .product_imgfiles object. Is that what you want? If so, that's good! If not, you should store those values as an attribute for each img element in PHP (eg data-product_token='$product_token' ) and then refer to them in JS with something like $(this).attr('data-product_token') or $(this).data('product_token') .

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