javascript 如何使用原型获取锚标记的父 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3289103/
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
How to get parent id of an anchor tag using prototype?
提问by Mohit Jain
Event.observe(window, 'load',
function() {
$$('a.tag_links').each(function(s) {
//alert(s.parent.parent.id); //How to get id of its parent to parent
});
}
);
I want to get the id of the parent element.
我想获取父元素的 id。
Structure is something like this.
结构是这样的。
<div class="home-page" id='entity-1'>
<div class="index-page-category">
<a href="/entities/category/food" class="tag_links">food</a>
</div>
Result should be entity-1
结果应该是 entity-1
回答by robjmills
Like this:
像这样:
$$('a.tag_links').each(function(s) {
var parentid = $(s).up('div').id;
});
回答by rickp
First, your HTML is incomplete. Does it look like:
首先,您的 HTML 不完整。是不是看起来像:
<div class="home-page" id='entity-1'>
<div class="index-page-category"></div>
<a href="/entities/category/food" class="tag_links">food</a>
</div>
Or like this:
或者像这样:
<div class="home-page" id='entity-1'>
<div class="index-page-category">
<a href="/entities/category/food" class="tag_links">food</a>
</div>
</div>
Either way, you should be able to achieve this by using:
无论哪种方式,您都应该能够通过使用:
$$('a.tag_links').each(function(s) {
var divId = $(s).previous('div.home-page').id;
});
I imagine the reason you're iterating through 'a.tag_links' is that you have a bunch of links? Based on that context, is that HTML structure always consistent (the outter div will always contain a class of 'home-page')?
我想你遍历 'a.tag_links' 的原因是你有一堆链接?基于该上下文,该 HTML 结构是否始终一致(外部 div 将始终包含一类“主页”)?

