Javascript获取外层父id DIV
我有一个如下所示的结构,我正在尝试获取 id foo
。如果我们从 onclick
func()
冒泡,它是唯一具有 id 的 DIV
,这意味着有不会是在 foo
中包含 id 的其他 DIV。但是,foo
内可以有其他包含 id 的标记(例如 bye, hello
)。
没有使用任何框架。
<div id="bar"></div>
<div id="foo">
<p><p>
<div class="bye">
<input id="bye" type="text" value="test" />
<input id="hello" type="text" value="test" />
<table>
<tr><td onclick="func(event)">1</td></tr>
<tr><td onclick="func(event)">2</td></tr>
</table>
</div>
</div>
I have a structure that looks like the one below, I'm trying to get the id foo
. It is the only DIV
with id if we bubble up from the onclick
func()
, which means that there wont be other DIVs that contain an id inside foo
. However, there can be other tags inside foo
that contain an id (such as bye, hello
).
No frameworks are being used.
<div id="bar"></div>
<div id="foo">
<p><p>
<div class="bye">
<input id="bye" type="text" value="test" />
<input id="hello" type="text" value="test" />
<table>
<tr><td onclick="func(event)">1</td></tr>
<tr><td onclick="func(event)">2</td></tr>
</table>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
函数
findIdOfParent
接受一个 DOM 节点。您可以使用onclick="findIdOfParent(this);"
调用它,但如果您只想传递event
(如您的示例所示),则必须提取来自event.target
的 DOM 节点或您当前正在执行的任何操作。The function
findIdOfParent
takes a DOM node. You could call it withonclick="findIdOfParent(this);"
, but if you only want to passevent
, as in your example, you'd have to extract the DOM node fromevent.target
or whatever you're currently doing.这应该可以做到:
This should do it:
您可以使用被单击元素的parentNode 属性来向上迭代DOM 树。
IE:
You could use the parentNode property of the clicked element to iterate up through the DOM tree.
ie:
elem 是单击时调用函数的元素
elem is the element that call the function on click
你不能应用更简单的模式吗?不要在单元格中设置 onclick 属性,而是将一个单击处理程序附加到最外层的 div,然后您只需引用
this
:http://jsfiddle.net/fRxYB/
还是我完全没有抓住要点?
Can't you apply a simpler pattern? Instead of having onclick properties in your cells, attach a single click handler to your outermost div(s), then you just need to refer to
this
:http://jsfiddle.net/fRxYB/
Or am I completely missing the point?
为了有一个更通用的版本,我建议这样:
例如:http://www.jsfiddle。净/4yUqL/37/
To have a somewhat more generic version, I'd suggest this:
example: http://www.jsfiddle.net/4yUqL/37/