问题
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>
回答1:
This should do it:
<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(this)">1</td></tr>
<tr><td onclick="func(this)">2</td></tr>
</table>
</div>
</div>
<script type="text/javascript">
function func(elt) {
// Traverse up until root hit or DIV with ID found
while (elt && (elt.tagName != "DIV" || !elt.id))
elt = elt.parentNode;
if (elt) // Check we found a DIV with an ID
alert(elt.id);
}
</script>
回答2:
function findIdOfParent(obj) {
var o = obj;
while(!o.id) {
o = o.parentNode;
}
alert(o.id); // 'foo'
}
The function findIdOfParent takes a DOM node. You could call it with onclick="findIdOfParent(this);", but if you only want to pass event, as in your example, you'd have to extract the DOM node from event.target or whatever you're currently doing.
回答3:
You could use the parentNode property of the clicked element to iterate up through the DOM tree.
ie:
<td onclick="func(this)">
function func(item)
{
var parent = item.parentNode;
// and so on, or something similar
var divId = div.id;
}
回答4:
elem is the element that call the function on click
var found = false;
var myId = "";
while (elem &&!found) {
if (elem.id){
found = true;
myId = elem.id;
}
elem = elem.parentNode;
}
回答5:
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:
document.getElementById("foo").onclick = function(event) {
if(e.target.tagName.toLowerCase() == "td") {
alert(this.id);
}
};
http://jsfiddle.net/fRxYB/
Or am I completely missing the point?
回答6:
To have a somewhat more generic version, I'd suggest this:
function func(event) {
var par = findTop(event.target);
console.log(par);
};
function findTop(node) {
while(node.parentNode && node.parentNode.nodeName !== 'BODY') {
node = node.parentNode;
}
return node;
}
example: http://www.jsfiddle.net/4yUqL/37/
来源:https://stackoverflow.com/questions/4658927/javascript-obtain-outer-parent-id-div