Javascript 在setAttribute中添加多个属性

Javascript 在setAttribute中添加多个属性,javascript,Javascript,如果我想使用setAttribute方法设置alt和scr属性,我需要两行还是可以将所有这些属性放在一行中 var imgEl=document.querySelectorAllimg; imgEl[0].setAttributesrc,images/image_1.jpg; imgEl[0]。setAttributealt,Image1; 我试过这个: imgEl[0].setAttributesrc,images/image_1.jpg,alt,Image1; 但这并不奏效 还有-这里是新手

如果我想使用setAttribute方法设置alt和scr属性,我需要两行还是可以将所有这些属性放在一行中

var imgEl=document.querySelectorAllimg; imgEl[0].setAttributesrc,images/image_1.jpg; imgEl[0]。setAttributealt,Image1; 我试过这个:

imgEl[0].setAttributesrc,images/image_1.jpg,alt,Image1; 但这并不奏效

还有-这里是新手!!!!我只是在尝试概念,而不是最佳实践:

您可以使用

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

setAttributes(imgEl[0], {
  {"attr1": "attr1val"},
  {"attr2": "attr2val"},
  {"attr3": "attr3val"}
});

你可以在这里找到答案:这行不通。setAttribute的返回值未定义。您将其与jQuery的.attr方法混淆。这不起作用。它只设置了列表中的第一个属性。@ShawnHayes更新了我的答案。