我有这样的html标签:
<il class="currItem" data-sourcemp3="http://**">
<il class="currItem" data-sourcemp4="http://**">
我想得到这个数据值,即使这个mp3或mp4 我写道:
var A = $('.currItem').attr("data-source(.+)")
console.log(A);
或者:
var srcName = new RegExp(/data-source.+/g);
var A = $('.currItem').attr(srcName)
console.log(A);
我得到&#34;未定义&#34;
我是怎么做到的? 提前致谢
答案 0 :(得分:1)
这是jQuery对你没有多大帮助的情况之一。可能最简单的只是循环遍历属性NamedNodeMap
:
var value;
var attrs = $('.currItem')[0].attributes;
for (var n = 0; n < attrs.length; ++n) {
if (/^data-source.+$/.test(attrs[n].name)) {
value = attrs[n].value;
break;
}
}
示例:
$(".currItem").click(function() {
var value = "(not found)";
var attrs = this.attributes;
for (var n = 0; n < attrs.length; ++n) {
if (/^data-source.+$/.test(attrs[n].name)) {
value = attrs[n].value;
break;
}
}
alert("Value: " + value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click a list item below:
<ul>
<li class="currItem" data-sourcemp3="http://**">xxxxx</li>
<li class="currItem" data-sourcemp4="http://**">xxxxx</li>
</ul>
&#13;
或者您可以遍历attributes
in many other ways,它是类似数组的对象。
答案 1 :(得分:1)
您可以使用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);
}
}
}
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;
}
}
}
<il class="currItem" data-sourcemp3="http://**"></il>
<il class="currItem" data-sourcemp4="http://Test.this"></il>