遍历 table 时获取 undefined 作为 span 标签的值

Getting undefined as the value for span tag while traversing a table

我需要使用 class = ustatus 到达 span 标签并为 id = foo 获取 jQuery 对象。

<tr>
  <td> <input name = 'user' type='radio 'id='foo'/> </td>
  <td> <input id='boo'/> </td>
  <td> <input id='too'/> </td>
  <td> <input id='yoo'/> </td>
  <td> <span class='ustatus'> Active </span> </td>
</tr>

我正在尝试:

$("input[name = 'user']:checked").closest('td').find('.ustatus').first().val()

但得到 undefined 作为值。我哪里弄错了?

您需要使用

$("input[name = 'user']:checked").closest('tr').find('.ustatus:first').text()

因为,ustatus 是你父母 td 的兄弟姐妹。所以需要先遍历到parenttr。然后你可以使用 find() 方法,它将搜索 child 元素

代码中的几个问题:

1) 你需要遍历到tr而不是td。因为 span 位于所选单选按钮的兄弟 td 之一中,父 td

2) span 元素关联了 text/html 属性 而不是 value.you 需要使用 .text()/.html() 而不是 .val()

3) 由于tr中只有一个ustatus元素,所以不需要.first()选择器。

$("input[name='user']:checked").closest('tr').find('.ustatus').text()

span has no value you need to use text() or html()

var text = $("input[name = 'user']:checked").parent().parent().find('.ustatus').text();

var html = $("input[name = 'user']:checked").parent().parent().find('.ustatus').html() ;

DEMO

因为你的锚点是输入,你需要进入 2 级到 tr,在那里你可以找到具有 class .ustatustd,所以你需要添加 2 parent()

您正在定位单元格,然后尝试使用 val()

查找第一个订单的“.ustatus”class 以获取 html content/value
$("input[name = 'user']:checked").closest('td').find('.ustatus').first().val() 

val() 用于获取表单字段的值。 使用 text()html() 分别获取纯文本内容或包含标签。

$("input[name ='user']:checked").closest('tr').find('.ustatus:first').text()

会起作用,因为我们在行中找到 .ustatus:first 并使用 text() 获取内容。