簡體   English   中英

jQuery:如何獲取多個img的src值

[英]jQuery : How To Get src Value of Multiple img

我有這個PHP腳本來生成目錄的縮略圖。 該目錄中的文件數量是動態的:

<?
    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>';
    }
?>

而且我也有這個jquery每次單擊縮略圖時都監聽事件:

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.' );
    });
}); 

';

jQuery部分能夠顯示警報消息。 但是,不幸的是,直到product_imgfiles數量增加並且循環顯示img標簽的src值相同,循環才會停止。

而我需要的是單擊class product_imgfiles類后獲取img標簽的src值。 單擊時如何獲取每個img類的每個src值? 謝謝。

刪除.each循環。

.click()已將其固有地應用於每個元素,您無需再次遍歷它們。

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.' );
    });
';

此外,您實際上需要將event變量傳遞到構造函數中。 正如在評論中提出來的,您引用被點擊與當前對象this ,而不是再次使用選擇。

而且,將產品令牌和秘密令牌與混淆位還有些奇怪。 每個.product_imgfiles對象都將相同。 那是你要的嗎? 如果是這樣,那就太好了! 如果不是,則應將這些值存儲為PHP中每個img元素的屬性(例如, data-product_token='$product_token' ),然后在JS中使用$(this).attr('data-product_token')$(this).data('product_token')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM