我可以更改 html 中的 img src 吗?

Can I change img src in html?

就像

<img src="somesrc" file="filepath" />

src 不正确 url,如何使用 url in file 属性为所有图像加载 img?

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery
/jquery-1.4.min.js"></script>

</head>

<body>

    <img src="wrongsrc" file="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"></img>

    <script >   
$("img").each(function(){
var filepath = $(this).prop("file");
if (filepath) this.src=filepath; 
}); 
</script>

</body>
</html>

我将我的代码改成了这个,但它不起作用。

使用 jQuery 编辑您的所有图片:

$(function() {    
  $("img").each(function(){
    var filepath = $(this).attr("file");
    if (filepath) this.src=filepath; 
  }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="wrongsrc" file="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"></img>
  <img src="wrongsrc" file="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"></img>
  <img src="wrongsrc" file="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"></img>
  <img src="wrongsrc" file="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"></img>

为每张图片添加一个id

对于HTML

<img SRC="somesource" id="1" />
<img SRC="somesource" id="2" />
<img SRC="somesource" id="3" />

对于JavaScript

(document).ready(function (){
$("img").each(function() {
var id = $(this).attr('id')
$(this).attr('src', ''+id+'_image.png');
});
});

重命名您的图片,如 1_image.PNG、2_image.PNG 等

这听起来令人困惑,但可能会起作用,请告知它是否可以在移动设备上运行,因此无法自行测试。

请使用另一个版本的 jQuery,它将正常工作。

jQuery("img").each(function(){
  var filepath = jQuery(this).attr("file");
  if (filepath) this.src=filepath; 
}); 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<img src="wrongsrc" file="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg">

上面的答案是正确的,当我 运行 它在 chrome 在 PC.But 当我把那个代码放在 ios 时,它似乎在那里在ios.Maybe中使用jQuery有点问题我没有在右边使用jQueryway.I使用下面的方法解决了我的问题:

    <script  type="text/javascript">
        var imgs = document.getElementsByTagName("img");
        for (var i = 0; i < imgs.length; i++) {
            if(imgs[i].getAttribute("file")!=null&&imgs[i].getAttribute("file")!=undefined){
                imgs[i].src=imgs[i].getAttribute("file");
            }
        }
    </script>