如何在jquery中构建HTML元素及其属性的数组?

时间:2014-07-07 19:08:07

标签: javascript jquery arrays

我正在尝试在jquery中构建一个数组数组来存储数据,并在我的代码中稍后使用它们。 我希望有这样的事情:

array[html_node][attribute] = attribute value

基于这种类型的DOM:

<div id= node>
  <a step= "downloading" data="123">
    ...
  </a>
  <a step= "waiting" data="122">
    ...
  </a>
</div>
你可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

虽然我同意之前的评论(为什么在DOM是一个非常好的替代品时创建一个存储数据数组?),这里有一些我认为你的东西。之后:

var arr = [];

$('#node a').each(function(){

  arr.push( $(this).attr('data') );

});

或许你想要node作为一个班级,其中会有多个nodes

var arr = [];

$('.node').each(function(i){

  arr.push([]);

  $(this).children('a').each(function(){

    arr[i].push( $(this).attr('data') );

  });
});

或者,如果您想要存储对节点的引用(使用数组很困难,因为在那里需要):

var arr = [];

$('.node').each(function(i){

  arr.push({ node:this, data:[] });

  $(this).children('a').each(function(){

    arr[i].data.push( $(this).attr('data') );

  });
});

Here's a fiddle(引用节点的id,以免扼杀JSON.stringify部分。

答案 1 :(得分:0)

我认为Javascript中隐藏的一个隐藏的宝石是数据结构的使用。特别是使用结构

对于你想要做的事情,几乎不可能像你想要的那样拥有布局

  

array [html_node] [attribute] =属性值

原因是,您必须为html_node分配数字,以便您必须对其进行硬编码,以便按照您希望的方式访问它们,或创建一些复杂的算法来检索该特定节点的值。

我在这里看到的另一个问题是,可能存在重复的html节点。这意味着,您可以拥有多个html_node 'DIV'个值,但它们具有不同的属性数据。无论如何,array[DIV]数组中只能有一个对象,因此还需要某种方式来区分每个节点。


您的解决方案:

Javascript Structs

这些具有超级灵活和易于访问的能力。

首先 - 您需要制作一个struct factory来初始化所有内容。 如果您不完全了解工厂,请不要担心,您需要做的就是复制并粘贴Javascript代码。 (但是,如果你能掌握这个概念,它还有帮助)

function makeStruct(names) {
  var names = names.split(' ');
  var count = names.length;
  function constructor() {
    for (var i = 0; i < count; i++) {
      this[names[i]] = arguments[i];
    }
  }
  return constructor;
}

第二次 - 创建结构并初始化数组

var HTML_Node = makeStruct("node step data");
var array = [];

第三次 - 向您的结构添加元素

$('#node').children().each(function(){
    array.push(new HTML_Node(this.nodeName, $(this).attr('step'), $(this).attr('data')));
});

第四 - 从你的结构中获取元素,这是一个非常简单的循环。

for(var i = 0; i < array.length; i++){
//All of these if statements will be referencing node / step / data as set up in step 2

    if(array[i].node == 'DIV'){
        //if the node is a DIV element do something
    }

    if(array[i].step == 'waiting'){
        //if the node's step is waiting do something
    }

    if(array[i].data == '123'){
        //if the node's data is 123 do something
    }
}

这就是如何使用结构创建一个简单的数据结构来存储所需的所有信息。