2017-08-28 230 views
0

我使用此代碼來改變形象src屬性數據src屬性,但它不工作,我不知道我做錯了任何幫助將是appreciated.Thanks如何在javascript中將img src屬性更改爲data-src?

<script> 

    $("img").each(function() { 
    $(this).attr("data-src",$(this).attr("src")); 
    $(this).removeAttr("src"); 
}); 

</script> 
    <img src="test.jpg" width="300" height="200"> 

我想這個輸出

<img data-src="test.jpg" width="300" height="200"> 
+1

此代碼應該工作的罰款。你確定'data-src' attr沒有出現在DOM中嗎?檢查元素。 – Utkanos

+0

你最好描述預期的結果。描述看起來很奇怪 – Anarion

+2

Javcascript代碼是否在'$(document).ready()'內? – Barmar

回答

-1

試試下面的代碼:

$("img").each(function() { 
 
    
 
     $(this).attr("data-src",$(this).attr("src")); 
 
     $(this).removeAttr("src"); 
 
     console.log($(this)[0].outerHTML); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script> 
 

 
    
 
    </script> 
 
     <img src="test.jpg" width="300" height="200">

+0

這會爲jQuery對象添加屬性,而不是DOM中可訪問的屬性。 – Utkanos

+0

我想要這個輸出 –

+0

@kumarsoni,這個解決方案適合你嗎? –

0

您需要在HTML中添加圖像後,像這樣來執行你的JS代碼:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img src="test.jpg" width="300" height="200"> 
 
<script> 
 

 
$("img").each(function() { 
 
    var $this = $(this); 
 
    var src = $this.attr("src"); 
 
    $this.attr("data-src", src); 
 
    $this.removeAttr("src"); 
 
}); 
 

 
</script>