[jQuery]数据数组绑定

问题描述 投票:0回答:1

我对包含在数据属性中的数组绑定有疑问。

场景:

<div class="rooms" data="room_14 room_10 room_9 room_5 room_4 room_12"></div>

我将数据推入数组,如下所示:

var dataTags = $(".rooms").data("tags");
var splitTags = dataTags.split(" ");

var arrayRooms = {
  "privilege": [],
  "standard": []
};

for ( i = 0; i < Roomslength; i++ ) {
   arrayRooms.privilege.push(splitTags[i]);
}

之后我必须在正确的 html 类名称上附加值(例如 class="room_11")

arrRooms.privilege.forEach(function(index,value){
  $('.'+index).html('Room '+parseInt(value + 1));
});

我需要将最低值的房间与 value = 0 相关联,在本例中为 room_4 并且有这种情况:

index: room_4 - value: 0 
index: room_5 - value: 1
index: room_9 - value: 2
index: room_10 - value: 3
index: room_12 - value: 4
index: room_14 - value: 5 

我该怎么办?

谢谢

jquery arrays data-binding
1个回答
0
投票

您正在尝试使用

$(".rooms").data("tags")
,但基于HTML,您应该使用数据而不是数据标签来访问数据属性,循环中也有一个错误,其中Roomslength应该由splitTags数组的长度确定.

$(document).ready(function() {
     var dataTags = $(".rooms").attr("data"); // Use .attr("data") instead of .data("tags")
     var splitTags = dataTags.split(" ");
 
     var arrayRooms = {
         "privilege": [],
         "standard": []
     };
 
     // sort splitTags based on the numeric part of the room IDs
     splitTags.sort(function(a, b) {
         return parseInt(a.substring(5)) - parseInt(b.substring(5));
     });
 
     // push sorted room IDs into the privilege array
     splitTags.forEach(function(tag) {
         arrayRooms.privilege.push(tag);
     });
 
     // update the html for each room based on its sorted position
     arrayRooms.privilege.forEach(function(roomId, index) {
         $('.' + roomId).html('Room ' + index);
     });
});     
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="rooms" data="room_14 room_10 room_9 room_5 room_4 room_12"></div>

© www.soinside.com 2019 - 2024. All rights reserved.