[英]Select data attribute based on matching part
How to select all data attributes starting with data-size-
in element like this one 如何选择以
data-size-
in元素开头的所有数据属性
<div class="el" data-name="str" data-size-100="str" data-size-158="str" data-size-304="str">str</div>
I'm trying to do something like, but can't figure it out: 我正在尝试做类似的事情,但无法弄清楚:
$('.el').attr('[data-size-*]')
You can achieve it by using dataset
您可以使用
dataset
来实现它
var data = $('.el')[0].dataset;
var attrs = Object.keys(data).reduce(function(a,b){
if(b.startsWith("size")){ a.push(data[b]); }
return a;
},[]);
console.log(attrs); \\ ["str","str","str"]
Here I used startsWith
to determine whether the data-'key' starts with a particular substring or not. 在这里,我使用
startsWith
来确定data-'key'是否以特定子字符串开头。 Also reduce
is to reduce the original key array to a new array based on the condition we have. 还
reduce
是根据我们的条件将原始键阵列减少到新阵列。
This one returns an array with objects holding both name and value. 这个返回一个数组,其中包含名称和值的对象。
var myDiv = document.getElementsByClassName("el")[0],
dataSizeAttrs = [];
Array.prototype.forEach.call(myDiv.attributes, e =>
/data-size/.test(e.nodeName) && dataSizeAttrs.push({name : e.nodeName,
value: e.nodeValue}) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.