如何使用javascript向图像添加属性?

如何使用javascript向图像添加属性?,javascript,html,image,Javascript,Html,Image,我想知道如何将图像属性添加到以下代码中。我添加了一个teest函数来查看用户浏览器是否支持webp图像,如果不支持,它只显示一个jpg图像而不是webp,但我想添加属性,我所做的一切都不起作用 function hasWebP() { var rv = $.Deferred(); var img = new Image(); img.onload = function() { rv.resolve(); }; img.onerror = function() { rv.rejec

我想知道如何将图像属性添加到以下代码中。我添加了一个teest函数来查看用户浏览器是否支持webp图像,如果不支持,它只显示一个jpg图像而不是webp,但我想添加属性,我所做的一切都不起作用

function hasWebP() {
  var rv = $.Deferred();
  var img = new Image();
  img.onload = function() { rv.resolve(); };
  img.onerror = function() { rv.reject(); };
  img.src = '/images/home/dot.webp';
  return rv.promise();
}
hasWebP().then(function() {
    var img=document.createElement("img");
    img.src="images/home/IMG_4389.webp";
    img.id="picture";
    var foo = document.getElementById("myFace");
    foo.appendChild(img);
}, function() {
    var img=document.createElement("img");
    img.src="images/home/IMG_4389.png";
    img.id="picture2";
    var foo = document.getElementById("myFace");
    foo.appendChild(img);
});
我把代码改成了

function hasWebP() {
  var rv = $.Deferred();
  var img = new Image();
  img.onload = function() { rv.resolve(); };
  img.onerror = function() { rv.reject(); };
  img.src = '/images/home/dot.webp';
  return rv.promise();
}
hasWebP().then(function() {
    document.getElementById("picture").src="/images/home/IMG_4389.webp";
}, function() {
    document.getElementById("picture").src="/images/home/IMG_4389.png";
});
并将其添加到我的html中

<img src="" id="picture" draggable="false">

您测试过img src URL吗?我用
img.src=“/images/home/img_4389.png”
进行了测试(注意src开头的/),它为我将图像附加到DOM中