Vanilla js相当于jquery .attr(attributeName,function)

问题描述 投票:1回答:1

我注意到jQuery .attr()有一个变体,它允许你为一个函数设置一个属性名:参见here

我试图找到与此相当的普通香草js,但请注意,setAttribute()函数似乎只允许您将属性值设置为字符串:请参阅here

更具体地说,我正在尝试将this article中的片段从jQuery转换为plain js:

$(function(){
  $('.stroke-double, .stroke-single').attr('title', function(){
    return $(this).html();
  });
});
javascript jquery
1个回答
2
投票

带有函数的jQuery的.attr对查询结果中的每个元素进行操作。等价物就像是

function attrEquiv(selector, attr, setterFunction) {
  document.querySelectorAll(selector).forEach((el, i) => {
    el.setAttribute(attr, setterFunction.call(el, i, attr)) // bind `el` to `this`
  })
}

attrEquiv('.stroke-double, .stroke-single', 'title', function(index, attr) {
  return this.innerHTML
})

ES5版本

var elements = document.querySelectorAll(selector)
Array.prototype.forEach.call(elements, function(el, i) {
  el.setAttribute(attr, setterFunction.call(el, i, attr))
})
© www.soinside.com 2019 - 2024. All rights reserved.