我们有一个约定,我们需要读取数据项元素集中的第一个数据项,但是我们发现firefox对数据项进行了排序,因此您不能依赖于返回的第一项。
var x = $("#x").data();
var y = "";
for (k in x) {
y += k + "=" + x[k] + ", ";
}
$("#x").text(y);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="x" data-xfirst="1" data-asecond="2">
</div>
如果在Edge或IE中运行此程序,则“正确”首先获取xfirst。如果您在firefox中运行它,您将获得第一秒。
编辑:刚刚在Chrome中尝试过,其行为与FF相同
我怎样才能按照它们在DOM中放置的顺序处理这些数据属性?
谢谢
最佳答案
data()
方法返回一个对象,该对象只是键值对的集合-不能保证它们如何存储和迭代,就像索引数组一样,其顺序不一样,并且在浏览器/ JS引擎之间会有所不同。 IE / Edge恰好适合您的特殊情况。
我认为您需要做的是使用outerHTML
分析元素的字符串。我相信这个字符串将包含它们在DOM中出现的数据属性(请在所有浏览器中进行测试)。然后,您只需要找到data-
属性的第一次出现。使用字符串的indexOf()
方法非常简单(或者您可以使用正则表达式):
const elemStr = document.getElementById('x').outerHTML;
const dataIndex = elemStr.indexOf('data-');
let quoteIndexes = [-1, -1];
// This is the first occurance of a data attribute
if (dataIndex > -1) {
// Find the opening and end quote indexes of the data attribute value
quoteIndexes[0] = elemStr.indexOf('"', dataIndex);
quoteIndexes[1] = elemStr.indexOf('"', quoteIndexes[0]+1);
if (quoteIndexes[0] > -1 && quoteIndexes[1] > -1) {
console.log(`First data attribute: ${elemStr.substring(dataIndex, quoteIndexes[1]+1)}`);
console.log(`Key: ${elemStr.substring(dataIndex+5, quoteIndexes[0]-1)}`);
console.log(`Value: ${elemStr.substring(quoteIndexes[0]+1, quoteIndexes[1])}`);
}
}
<div id="x" style="width:100px;" data-name="test" data-class="foo" data-type="bar" class="some classes"></div>