【问题标题】:Dynamically add rows into a table using data from another table-jQuery使用来自另一个表的数据动态地将行添加到表中-jQuery
【发布时间】:2013-12-09 00:43:49
【问题描述】:

我的页面上有两个表格,如图所示。

我想做的是:

  1. 在源表中选择行
  2. 从源表中读取ID字段、名称字段的数据,以及单选按钮的值。
  3. 将这些数据形成目标表的行并将这些行附加到目标表中。

现在我使用两个数组来存储从源表读取的 ID 和名称,但我对如何为目标表形成一行有点困惑。

$('#btnLinkCase').click(function (event) {
var caseID = $('#caseID').text();
var linkedIDArr = []; //array list for selected id
var linkedNameArr = []; //array list for selected name
$('#linkCaseTable tbody tr td:nth-child(2)').each(function (index, el) { //store each paire of <tr> into array
    linkedIDArr.push(el);
});
$('#linkCaseTable tbody tr td:last-child').each(function (index, el) { //store each paire of <tr> into array
    linkedNameArr.push(el);
});
$.each(linkedCaseIDArr, function (index, val) {
    //whats next?
});
});

请查看全部源码here

有这样做的想法吗?提前致谢

编辑: 如果选择了多行,它们将使用单选按钮中的相同值。例如:选择了两行并选中了“Type 1”。在目标表中,它们的关系都是“Type 1”。我希望我已经解释了自己..

【问题讨论】:

  • 目标表只需要ID、名称和类型吗?然后 `var object = [{'name': 'value'}, {'ID': 'value'}, {'type': 'value'}];
  • 是的,只需要 ID、Name 和 Type。您的意思是将对象存储到数组中吗?然后使用数组形成目标表的行?你能给我一个 jsFiddle 演示吗?

标签: javascript jquery html


【解决方案1】:

试试:

$('button').click(function (event) {
    $("#sourceTable tr:gt(0)").each(function(){
        var th = $(this);
        console.log("dfg")
        if($(th).find("input[name='link-cbx']").is(":checked")){ //assuming ids are unique remove condition if you do notwant so
            var id = $(th).find("td:eq(1)").text();
            var name = $(th).find("td:eq(7)").text();
            var type = "Type "+$("input[name='linkType']:checked").val();
            if($("#targetTable:contains('"+id+"')").length < 1){            
                $("#targetTable").append("<tr><td>"+id+"</td><td>"+name+"</td><td>"+type+"</td></tr>");
            }
        }
    });
});

Updated fiddle here.

【讨论】:

  • in your code, when select Type 2 the target table will only display Type 1, change the value of type2 to "2"
  • 非常感谢!它完美无缺!并防止我的目标表中出现重复的 ID。
  • @Twocode 因为我的html,2个单选按钮的值都是“1”,当我将第二个单选按钮的值更改为“2”时它工作正常
猜你喜欢
  • 2014-03-06
  • 2021-12-13
  • 2011-05-09
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
相关资源
最近更新 更多