Internet Explorer 7 返回“未定义”来自 jQuery 类选择器
我有一个小的 JavaScript 函数,它(除其他外)检索具有特定类名的最后一个元素的 ID。
var lastRowID = $(".sectionRow:last").attr('id');
它应该在表中找到类似于以下内容的元素:
<table>
<tr id="courseSection[0]" class="sectionRow"><td>stuff</td></tr>
<tr id="courseSection[1]" class="sectionRow"><td>more stuff</td><td><a href="javascript:removeSectionRow(1)">(remove)</a></td><td><a href="javascript:addSectionRow()">(add additional row)</a></td></tr>
</table>
如果我执行快速 alert(lastRowID)
,我会在 Chrome、Firefox 和 IE8 中得到“courseSection[1]”。然而,IE7 讨厌我并说“未定义”。
注意:我也尝试过 $(".sectionRow").last().attr('id')
但没有成功。
对可能发生的事情有什么想法吗?谢谢!
编辑:此表是使用 javascript 通过单击按钮添加的(按钮显示/添加表单的下一部分)。所以页面加载时 DOM 中的不是静态 html。
单击删除链接时将调用removeSectionRow(n) 函数。它删除指定的行,然后搜索类名“sectionRow”剩余的最后一行,以便为该行提供“添加附加行”链接。这个想法是用户可以随意添加和删除行。这是最终结果的屏幕截图,以说明我可能解释得不好的内容:http://imgur.com/uXYHj。 .png
I have a small JavaScript function that (among other things) retrieves the ID of the last element with a certain class name.
var lastRowID = $(".sectionRow:last").attr('id');
It should find elements in a table that looks similar to the following:
<table>
<tr id="courseSection[0]" class="sectionRow"><td>stuff</td></tr>
<tr id="courseSection[1]" class="sectionRow"><td>more stuff</td><td><a href="javascript:removeSectionRow(1)">(remove)</a></td><td><a href="javascript:addSectionRow()">(add additional row)</a></td></tr>
</table>
If I do a quick alert(lastRowID)
, I get 'courseSection[1]' in Chrome, Firefox, and IE8. However, IE7 hates me and says 'undefined'.
Note: I've also tried $(".sectionRow").last().attr('id')
to no success.
Any thoughts on what might be going on? Thanks!
Edit: This table was added using javascript on a button click (button shows / adds next part of the form). So it's not static html that was in the DOM at page load.
The removeSectionRow(n) function is called when the remove link is clicked. It removes the specified row, then searches for the last row remaining with class name "sectionRow" in order to give that row a "add additional row" link. The idea being that the user can add and remove rows at will. Here's a screenshot of the finished result to illustrate what I'm probably poorly explaining: http://imgur.com/uXYHj.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符
[
和]
不是有效的 ID 字符。也许这会导致 IE7 出现一些问题。测试选择器返回的元素数量,看看是否获得
。
The characters
[
and]
are not valid ID characters. Perhaps this is causing some issue in IE7.Test the quantity of elements returned by the selector to see if you are getting the
<tr>
or not.也许是因为它是无效的 HTML?您需要其中的
标签。对我来说适用于 IE8。
http://jsfiddle.net/VCpZq/
Maybe because it's invalid HTML? You need
<td>
tags in there. Works in IE8 for me.http://jsfiddle.net/VCpZq/