在鼠标单击时使用JQuery从表中获取数据

时间:2013-03-13 17:37:30

标签: jquery

我有一个页面,其中有一个使用CodeIgniter的表类生成的表。 现在可以通过使用JQuery单击它来获取<td>标记的内容。 例如 我的表是这样的:

<table>
<th>ID</th><th>Name</th><th>Age</th>
<tr><td>25</td><td>Jack</td><td>15</td></tr>
<tr><td>20</td><td>Jill</td><td>16</td></tr>
</table>

如何在单击标签时获取标签内的内容(文本)?

4 个答案:

答案 0 :(得分:3)

$('table td').click(function() { 
    var text = $(this).text(); 
});

答案 1 :(得分:2)

使用此:

$("table td").click(function(){
    alert($(this).text());
});

或者:

$("table td").click(function(){
    alert(this.innerText);
});

Fiddle

答案 2 :(得分:1)

你可以这样做......

JS:

$('table td').click(function() {
var mvalue = $(this).text(); /*you can store in in a variable and use it for something else later*/
alert(mvalue); /*this provides a popup on top of the screen*/
console.log(mvalue); /*this shows you the value in your web console in case you are debugging*/
});

查看我的fiddle了解演示

答案 3 :(得分:1)

我更喜欢使用链接,它更加用户友好:

HTML:

...
<tr>
    <td><a href="#">25</a></td>
    <td><a href="#">Jack</a></td>
    <td><a href="#"15</a></td>
</tr>
...

的javascript:

$('a').click(function(event) {
    event.preventDefault();
    var text = $(this).text(); 
});