很抱歉,我已将代码更改为:
<table border="1">
<?php
$a = array('apple','banana','grapes','pineapple');
for ($x=0;$x<=3;$x++)
{
?>
<tr>
<td><div class='fruit' ><?php echo $a[$x]; ?></div></td>
<td><a href='#' class='viewbutton'>View</a></td>
</tr>
<?php
}
?>
</table>
现在我的问题是如何获取 <div>
中的文本?我试过$(".viewbutton").click(function() { alert ( $('#div_debit').text() ); });
这将仅返回第一个值。如何获取数组中的后续值?是使用id吗?
最佳答案
据我所知,没有 CSS 或 jQuery 特定的选择器来匹配所有数值(例如正则表达式中的 [0-9]
或 \d
);如果我错了,请纠正我!
但是:当你给每个<span>
时“水果”类,您可以使用 span.fruit
访问它们。这将返回一个数组,您可以使用 each()
对其进行迭代。 。 this
将被设置为该函数中的当前项目,因此您可以检查所需的 ID。
$('.fruit').each(function(){
// this.id will be your numeric ID of the current item
});
此外,如果您的元素连续编号(例如 1、2、3,而不是 2、1、3),则可以使用 :nth-child
-pseudo-selector访问 <span>
之一s。
如果这一切都不适合你;例如如果您需要使用类 .fruit
在其他地方也是如此,我能想到的最后一个选择是手动迭代 JavaScript 中的元素。
for( var x = 0; x <= 3; x++ ) {
var e = $('#'+x);
// Do something with the element; or add it to an array of all the elements
}
编辑:如果您不知道页面中有多少项,但希望匹配每个数字 ID,则可以使用以下内容。
$('*').each(function(){
if( this.id.match(/\d+/) ) {
// do something with an element which has a numeric ID
}
});
当然,如果您知道会有多少项,最好使用上面的示例,因为它可能会更快。
关于jquery - 如何使用 jQuery 获取带有增量 id 的跨度文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7621463/