2014-10-10 28 views
0

我有一个具有多行结构的html表。从选定的tr获取特定css类的值

我可以选择通过jQuery点击行,但现在我想要获得一个特定的字段的值与CSS类“书”在行内。

$(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访问按钮的值?

+0

使用$(this).find('。book')。text() – 2014-10-10 12:07:26

+1

@AlexG那么,这是有效的!但你能告诉我为什么吗?还加入这个答案,以便我可以接受它! – KhorneHoly 2014-10-10 12:08:36

+0

@KhorneHoly'val()'方法用于获取输入元素的值,例如'input','select'和'textarea'。既然你想要一个'td'的内容,你需要使用'.text()'或'.html()'根据你的需要 – 2014-10-10 12:10:21

回答

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()1用于输入,选择和文本区域。这就是为什么它不适用于你的代码。

+0

谢谢你的解释! – KhorneHoly 2014-10-10 12:14:29