简体   繁体   English

从数组中获取正确元素的正确方法

[英]right way to get the correct element from array

I have the following two arrays: 我有以下两个数组:

var nodes = new Array();
var arr = [{
        name:"abc1",
        type:"blue"
    }, {
        name:"abc2",
        type:"red"
    }, {
        name:"abc3",
        type:"red"
    }, {
        name:"abc4",
        type:"green"
    }, {
        name:"abc5",
        type:"red"
    }, {
        name:"abc6",
        type:"blue"
    }];

Reading the info from " arr " I have got a table with 2 rows where no info on the elements with type not " blue " is given: 从“ arr ”读取信息,我得到了一个包含2行的表,其中未给出非“ blue ”类型元素的信息:

 ---------------------
 |    | name | type  |  } - thead
 ---------------------
 | [] | abc1 | blue  |  } - 1st row
 ---------------------   
 | [] | abc6 | blue  |  } - 2nd row
 ---------------------

The checkbox element of each row has a class " table_row_checkboxes " 每行的复选框元素都有一个类“ table_row_checkboxes

Clicking on a checkbox in a row I find the index of the whole row. 单击一行中的复选框,我会找到整行的索引。 Than I test if the checkbox checked or not. 比我测试该复选框是否已选中。 If it is, than fill the new array called " nodes " with the names. 如果是这样,则用名称填充名为“ nodes ”的新数组。 If it is not, than empty the array. 如果不是,则清空数组。

$(".table_row_checkboxes").click(function(){
    var idx = $(this).closest("tr").index(); // row index of the table

    if ($(this).is(":checked")) {
        nodes.push(arr[idx].name);
    } else if($(this).not(":checked")) {
        nodes = $.grep(nodes, function(val_name) {
            return val_name != arr[idx].name;
        });
    }
}

Now my problem is, when I click on the element of the table with name " abc6 " I get the index number " 1 " of the element, which corresponds to the element " abc2 " in " arr ", and my new array " nodes " is filled with name " abc2 " instead of " abc6 ". 现在我的问题是,当我单击名称为“ abc6 ”的表的元素时,我得到了该元素的索引号“ 1 ”,它对应于“ arr ”中的元素“ abc 2 ”以及新数组“ node” “”以名称“ abc2 ”而不是“ abc6 ”填充。

My question is, can someone give me a hint, which gets it right? 我的问题是,有人可以给我一个提示,正确吗?

The problem is that you don't have a connection between your array and the created table. 问题是您的数组和创建的表之间没有连接。

I would suggest to set a custom attribute to the table row (tr) ( Custom Data Attributes ) and read this on click. 我建议将自定义属性设置为表行(tr)(“ 自定义数据属性” ),并在单击时阅读。

Your table row html should look like: 您的表格行html应该如下所示:

<tr data-array-index="5">[...]</tr>

Now you can retrieve the array index of the row via: 现在,您可以通过以下方式检索行的数组索引:

$(".table_row_checkboxes").click(function(){
    var arrayIndex = $(this).closest("tr").attr("data-array-index");
    [...]

I did not test it. 我没有测试。 But I think the approach is right. 但是我认为这种方法是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM