访问不同类型的元素

时间:2014-09-04 20:43:16

标签: javascript jquery

我有一张几行的表格。每行都有标题,数据和隐藏字段。数据列可以包含文本或文本区域。

<table id="knowledgeTreeTable" class="custom">
<tbody>
  ....................
  <tr>
     <th class="">What is the name of the party?</th>
     <td class="">
        <textarea id="ktField_7" class="ktEdit" type="text"></textarea>
     </td>
     <input id="ktField_7H" type="hidden" value="Unique contested">
  </tr>
  <tr>
     <th class="">What is the name of the opposing party?</th>
     <td class="">
        <input id="ktField_8" class="ktEdit" type="text" style="width: 97%;">
     </td>
     <input id="ktField_8H" type="hidden" value="Query">
  </tr>
  ......................
</tbody>
</table>

我能够读取标题和隐藏字段的内容,但不知道如何读取数据列,因为它可以有两种不同类型的元素。

$("#knowledgeTreeTable tr").each(function() {
        alert($('th', this).text());//OK
        //alert($('td > [input, textarea]', this).val()); // This is not OK.
        alert($('input', this).val());//OK
    });

3 个答案:

答案 0 :(得分:2)

您无法对选择器进行分组,例如

td > [input, textarea]

相反,请使用

td > input, td > textarea

答案 1 :(得分:1)

就像在CSS选择器中一样,查找 both

alert($('td > input, td > textarea', this).val()); 

虽然因为你同时使用同一个课程,但我倾向于使用:

alert($('td > .ktEdit', this).val()); 

答案 2 :(得分:0)

每当您尝试在这样的循环中访问子元素时,您需要确定每个元素之间的公共因子是什么。在这种情况下,它们是具有不同名称的不同标签,但它们都具有ktEdit类,并且都具有type="text"(我不相信它实际上适用于textareas)。

在这种情况下,公共变量是类名,因此您可以将其用作选择器。只要您正确定位父循环,如果您在整个页面中的其他元素上使用该类,那将无关紧要:

$("#knowledgeTreeTable tr").each(function() {
    alert($('.ktEdit', this).val());
});
相关问题