通过 javascript 根据自定义数据属性对 div 进行排序

Sort divs based on custom data attributes via javascript

我有一个 div 的列表。每个 div 都包含一个名为 "data-target" 的自定义数据属性。数据目标包含数字。这些数字与顺序无关。

通过 Javascript 我想为 div 的正确顺序创建一个列表。

例如: - 如果自定义属性为“4321”,则设置位置 1。 - 自定义属性为“5849”的位置设置为 2。 ...

您可以在下面找到我正在考虑的示例,但它不起作用。

HTML/CSS

<html>
<head>
<style> 
#main {
  width: 400px;
  height: 100px;
  border: 1px solid #000000;
  display: flex;
}

#main div {
  width: 70px;
  height: 70px;
}
</style>
</head>
<body>

<div id="main">
    <div style="background-color:green;" data-target="111222"> </div>
    <div style="background-color:blue;" data-target="222333"> </div>
</div>

<button onclick="myFunction()">Try it</button>

JAVASCRIPT


<script>


function myFunction() {

    $('[data-target="111222"]').style.order = "2";
    $('[data-target="222333"]').style.order = "1";

}


</script>

绿色背景的第一个div应该切换到第二个位置。我在这里找到了一个有效的示例,但它是由 ElementID 而不是自定义数据属性调用的:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_order

在您的浏览器控制台中,您应该会收到以下错误消息:

Uncaught TypeError: Cannot set property 'order' of undefined

这意味着 jQuery 对象没有名为 style 的 属性,这就是它像 undefined 一样对待它的原因。如果要修改 jQuery 对象的 css 属性,请改用 .css()。您的代码应如下所示:

$('div[data-target="111222"]').css('order', '2');
$('div[data-target="222333"]').css('order', '1');

附上一个Fiddle.

试试这个:

function myFunction() {

    document.querySelector('div[data-target="111222"]').style.order = "2";
    document.querySelector('div[data-target="222333"]').style.order = "1";

}
<html>
<head>
<style> 
#main {
  width: 400px;
  height: 100px;
  border: 1px solid #000000;
  display: flex;
}

#main div {
  width: 70px;
  height: 70px;
}
</style>
</head>
<body>

<div id="main">
    <div style="background-color:green;" data-target="111222"> </div>
    <div style="background-color:blue;" data-target="222333"> </div>
</div>

<button onclick="myFunction()">Try it</button>