从表中获取jsonArray

时间:2013-11-15 19:14:40

标签: javascript jquery json

我有一个表,需要构建json数组。我需要表格的第1列和第4列的值。

HTML

<table class="table table-striped" id="development_mapping">
                                <thead>
                                    <tr>
                                        <th>Visual Feature</th>
                                        <th>Step</th>
                                        <th>Output</th>
                                        <th>Data Feature</th>
                                    </tr>
                                </thead>
                                <tbody>                      
                                <tr><td>color</td> 
                                        <td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
                                        <td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
                                        <td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>                                        
                            </table>

这是我的解决方案,一个从表

创建json数组的函数

JAVASCRIPT

var jsonArray = {};

$('#development_mapping').find('tr').each(function () {
    var name = $(this).find('td:first').text(); 

    jsonArray[name] = {

          variable : $(this).find('td:eq(3)').text()

    }; 
});

我已经完成但不明白,为什么我从4列的值获得" "。我的意思是,为什么变量中的变量总是得到" "

这是我的DEMO

3 个答案:

答案 0 :(得分:1)

您的选择器:$('#development_mapping').find('tr')正在选择表格中的所有 <tr>标签。即使是<thead>中的那个! <thead>没有<td>个标签,因此" "来自哪里。

试试这个:

$('#development_mapping').find('tbody tr').each(function () {
    var name = $(this).find('td:first').text(); 

    jsonArray[name] = {

          variable : $(this).find('td:eq(3)').text()

    }; 
});

答案 1 :(得分:0)

您使用的是.text(),但第3个td代码中没有实际文字。

试试这个吗?

variable : $(this).find('td:eq(3) input').val()

答案 2 :(得分:0)

您的代码有两个问题。

  1. 删除表头定义中的周围<tr>
  2. 使用此选项可访问输入值

    variable: $(this).find('td:eq(3) > input').first().val()

  3. $.find()将返回一个集合,您需要获取该集合的第一个对象以供进一步使用。另外,您需要在单元格内搜索输入,而不是单元格本身。

    这是工作小提琴:http://jsfiddle.net/toshkaexe/7q3KP/

相关问题