访问jquery中的兄弟姐妹

时间:2012-10-24 08:17:56

标签: javascript jquery

这是我的代码:

<table><tr><td>hello</td>
       <td><input type="text" value="0" onkeypress="GetValue();" /></td>
       <td><input type="text" value="15"  /></td>
       </tr>
 </table>
   <script type="text/javascript">
   function GetValue(){
      //  ???

       }
   </script>

我如何访问第三个td的值(td值为15) 不使用简单的方法并给td一个id并通过使用.parent()或.siblings()来调用它我这是一个简单的例子来简化我的工作但是在我的实际项目中输入的值是从DB绑定的而任何帮助apreciated都要复杂得多。

5 个答案:

答案 0 :(得分:3)

您可以通过:nth-​​child()选择器完成此操作。

JS代码:

$('table td:nth-child(3) input').val();

DEMO

答案 1 :(得分:2)

您应该将DOM元素传递给GetValue函数:

<input type="text" value="0" onkeypress="GetValue(this);" />

使用jQuery方法从下一个文本字段中获取值:

function GetValue(that) {
    var val = $(that).parent().next().find("input").val();
}

DEMO: http://jsfiddle.net/xzzUB/1/

答案 2 :(得分:0)

像这样更改输入:

<input type="text" value="0" onkeypress="GetValue(this);" />

和功能:

function GetValue(el){
  var sib = $(el).parent().siblings('td').last();
}

答案 3 :(得分:0)

$("td:eq(2) input").val()将返回15

请参阅:http://docs.jquery.com/Selectors/eq

答案 4 :(得分:-1)

HTML

<table id='theTable'><tr><td>hello</td>
       <td><input type="text" value="0" onkeypress="GetValue();" /></td>
       <td><input type="text" value="15"  /></td>
       </tr>
 </table>​​​

使用nth-child()jQuery函数

console.log($('#theTable td:nth-child(3)').children().val());​​​​​