从选定的tr中获取特定css类的值

时间:2014-10-10 12:06:06

标签: javascript jquery html

我有一个包含多行的html表,这些行的结构都是相同的。

我可以通过jQuery选择点击的行,但现在我想获得某个字段的值,其中css类“book”位于该行中。

$(function(){
    $(document).on('click', '.book_listing', function(){
        $(this).css('background', 'red');
        // That's the code I tried to get the val
        console.log($(this).find('.book').val());
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>Stuff 1</th>
      <th>Stuff 2</th>
      <th>Stuff 3</th>
    </tr>
  </thead>
  <tbody>
    <tr class="book_listing">
      <td><button class="book">The value I want</button></td>
      <td>Other stuff</td>
      <td>and so on</td>
    </tr>
  </tbody>
</table>

但我不是上面代码中按钮的值。

如何从所选的tr?

中访问按钮的值

1 个答案:

答案 0 :(得分:2)

你需要使用

$(this).find('.book').text()

或者您可以使用

$(this).find('.book').html()

如果您使用.text(),那么您将获得文本,如果您使用.html(),您将获得带有标记的文本。 示例

<button class="book">The value I <b>want</b></button>

.text() will return: The value I want
.html() will return: The value I <b>want</b>

.val()我用于输入,选择和textarea。这就是为什么它没有为你的代码工作。