javascript - Vanilla js equivalent of jquery .attr( attributeName, function )
问题描述
I note that jQuery .attr()
has a variant which allows you to set an attribute name to a function: see here.
I'm trying to find the plain vanilla js equivalent of this, but note that the setAttribute()
function only appears to allow you to set an attribute value to a string: see here.
More specifically, I'm trying to convert a snippet from this article from jQuery to plain js:
$(function(){
$('.stroke-double, .stroke-single').attr('title', function(){
return $(this).html();
});
});
解决方案
.attr
带有函数的 jQuery对查询结果中的每个元素进行操作。相当于
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))
})
推荐阅读
- python-3.x - 无法在 Mac 上安装 AWS CLI
- javascript - 在 React.js 电子商务项目中实现“AddToCard”
- java - 递归循环再次运行而无需在 Java 中调用它
- android - 如何调整 2 个动态 android 布局的大小以填充可用空间,如果两者都想要超过一半,则每个都使用一半?
- spring-boot - 如何定期检查条件直到它通过或持续时间到期
- python - 为什么 python 乘以两个 n 位整数所花费的时间仅在 n 在 10 秒内增加时才会增加?
- sql - Sqlboiler 只获取所需的列
- javascript - 使用节点 js 运行不和谐机器人时出错
- flutter - 如何左右移动小部件直到可用空间被填满?
- python - 将日期时间更改为字符串