javascript 返回 tr 标签的“value”属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15211904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return "value" attribute of a tr tag
提问by Mildfire
I have the following table:
我有下表:
<table id="messages" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Text</th>
<th>Subject</th>
</tr>
<tr value="1">
//data
</tr>
<tr value="2">
//data
</tr>
</tbody>
</table>
I need some jquery that will return the val attribute of the clicked tr. I already have jquery that will return an array of all teh inclosed td within the tr but i still need the "value" saved to a variable. Any help?
我需要一些 jquery 来返回被点击的 tr 的 val 属性。我已经有了 jquery,它将返回 tr 内所有封闭 td 的数组,但我仍然需要将“值”保存到变量中。有什么帮助吗?
回答by Blazemonger
It's not advisable to add value
attributes to non-input elements, because that makes no sense to the browser. Change <tr value="1">
to <tr data-value="1">
and access it using $tr.data('value')
(where $tr
is a jQuery object for oneunique table row).
value
向非输入元素添加属性是不可取的,因为这对浏览器没有意义。更改<tr value="1">
到<tr data-value="1">
并使用访问它$tr.data('value')
(这里$tr
是一个jQuery对象一个唯一的表行)。
回答by Guffa
You would use $(this).attr('value')
to get the attribute, but some browsers might not support a non-standard attribute like this. It would be better to use a data attribute:
您将使用$(this).attr('value')
获取属性,但某些浏览器可能不支持这样的非标准属性。最好使用数据属性:
<tr data-value="1">
Then you can get the value using $(this).data('value')
.
然后您可以使用$(this).data('value')
.
回答by Juan Guzmán
With Jquery
使用jQuery
var variable = $('tr').val();
var variable = $('tr').val();
Or
或者
var variable = $('tr').attr('value');
var variable = $('tr').attr('value');
Even when it's incorrect to assign a value to a tr element
即使给 tr 元素赋值是不正确的