我有这样的html标签:
<il class="currItem" data-sourcemp3="http://**">
<il class="currItem" data-sourcemp4="http://**">
Run Code Online (Sandbox Code Playgroud)
我想得到这个数据值,即使这个mp3或mp4我写道:
var A = $('.currItem').attr("data-source(.+)")
console.log(A);
Run Code Online (Sandbox Code Playgroud)
要么:
var srcName = new RegExp(/data-source.+/g);
var A = $('.currItem').attr(srcName)
console.log(A);
Run Code Online (Sandbox Code Playgroud)
我得到"未定义"
我是怎么做到的 提前致谢
您可以使用来获取元素上存在的dataset所有属性的列表,然后迭代所有这些属性。data-*
// Select all the elements having the class
var allEl = document.querySelectorAll('.currItem');
// Regex for data attribute
var regex = /^sourcemp\d+$/;
// Iterate over all the elements
for (var i = 0; i < allEl.length; i++) {
// Get the list of all available data-* attributes on current item
var data = Object.keys(allEl[i].dataset);
// Iterate over the all data-* attributes
for (var j = 0; j < data.length; j++) {
// Check if this is the data attribute we're interested in
if (regex.test(data[j])) {
// Get value of the it
var value = allEl[i].getAttribute('data-' + data[j]);
console.log(value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
// Select all the elements having the class
var allEl = document.querySelectorAll('.currItem');
// Regex for data attribute
var regex = /^sourcemp\d+$/;
// Iterate over all the elements
for (var i = 0; i < allEl.length; i++) {
// Get the list of all available data-* attributes on current item
var data = Object.keys(allEl[i].dataset);
// Iterate over the all data-* attributes
for (var j = 0; j < data.length; j++) {
// Check if this is the data attribute we're interested in
if (regex.test(data[j])) {
// Get value of the it
var value = allEl[i].getAttribute('data-' + data[j]);
console.log(value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
var allEl = document.querySelectorAll('.currItem');
var regex = /^sourcemp\d+$/;
for (var i = 0; i < allEl.length; i++) {
var data = Object.keys(allEl[i].dataset);
for (var j = 0; j < data.length; j++) {
if (regex.test(data[j])) {
var value = allEl[i].getAttribute('data-' + data[j]);
console.log(value);
// For Demo
document.body.innerHTML += '<br />Data attribute = ' + data[j] + ' value = ' + value;
}
}
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
487 次 |
| 最近记录: |