如何使用 jQuery 查找元素的 id
这是我遍历父母的html代码
< body >
< div id="map" >
,直到找到主体
var pageFrom= $(theElement).parentsUntil( 'body' );
var pageFromId = $(pageFrom).attr("id");
在firebug中找到地图我看到pageFrom [div#map.current]
问题是pageFromId是“”,它应该是“map”
This is the html code
< body >
< div id="map" >
I am traversing the parents until I find the body to find the map
var pageFrom= $(theElement).parentsUntil( 'body' );
var pageFromId = $(pageFrom).attr("id");
in firebug i see pageFrom [div#map.current]
The problem is that pageFromId is "" and it should be "map"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用的是
parentsUntil()
[docs]< /i> 方法,它正在重新调整祖先的集合,从距离起点最近的到距离最远的。因此,您需要访问集合中的最后一个来获取其 ID。
或
请注意,您还可以获取 ID 作为元素的属性:
If you're using the
parentsUntil()
[docs] method, it is retuning a collection of ancestors ordered from those nearest the starting point to those farthest away.Because of this, you'll need to access the last one in the collection to get its ID.
or
Note that you can also grab the ID as a property on the element:
试试这个:
try this:
或许
?
但你应该更具体地说明你需要什么。你真的需要元素和主体之间的所有父母吗?否则,您可以使用.closest。
另外,在您的初始代码中,您不需要使用
$(pageFrom)
因为它已经是一个 jquery 对象。Maybe
?
But you should be more specific about what you need. Do you really need all the parents between the element and body? Otherwise, you can use .closest.
Also, in your inital code, you don't need to use
$(pageFrom)
since it's already a jquery object.我不太清楚你在这里问什么。但是,如果这里的模式是
之后的第一个
有一个 ID,而这就是您想要获取的内容,那么简单因为这应该可以解决问题:
没有理由向上遍历到文档的主体——应该总是有一个,所以为什么不从那里开始并向下工作呢?
I'm not quite sure what you're asking here. But if the pattern here is that the first
<div>
after the<body>
has an ID, and that's what you're trying to grab, something as simple as this should do the trick:There's no reason to traverse upward to the document's body -- there should always be one, so why not start there and work down?
来自文档:
这意味着您尝试在元素数组上调用 attr,而不是最终元素本身。你到底想做什么?您想查找正文中的第一个元素,还是想查找与选择器匹配的最接近的元素?
From the docs:
That means you're attempting to call
attr
on an array of elements, not the final element itself. What exactly is it that you want to do? Do you want to find the first element within the body, or do you want to find the closest element that matches a selector?