HTML代碼的子節點:的Javascript得到一個div
<div id="section">
<div id="title" onclick="hideBody()"></div>
<div id="body"></div>
</div>
我如何可以訪問使用this.
的id="body"
元素...?
實例:
this.parent.child[1];
HTML代碼的子節點:的Javascript得到一個div
<div id="section">
<div id="title" onclick="hideBody()"></div>
<div id="body"></div>
</div>
我如何可以訪問使用this.
的id="body"
元素...?
實例:
this.parent.child[1];
您可以使用nextElementSibling
。
實施例:
function hideBody(el) {
'use strict';
var sibling = el.nextElementSibling;
console.log(sibling);
sibling.style.visibility = 'hidden';
}
參見jsFiddle。
至於回答關於子節點的原始問題,有一個childNodes
屬性。例如:
var children = document.getElementById('section').childNodes;
相對於 「this
」(在hideBody函數示出):
function hideBody(el) {
'use strict';
var children = el.parentNode.childNodes;
console.log(children);
children[1].style.visibility = 'hidden';
}
我不知道用 '這個' 爲宜這裏,但你當然可以傳遞事件,抓住點擊目標的ID:
http://jsfiddle.net/isherwood/6k7fc/
<div id="title" onclick="hideBody(event)"></div>
function hideBody(event) {
var myId = event.target.id;
var myEl = document.getElementById(myId);
... do stuff with myEl ...
}
[獲取該燒製使用jQuery一個事件的元素的ID]的可能重複(HTTP:/ /stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event-using-jquery) – isherwood
什麼是「this」?提供更多信息。 –
@AlfredoOsorio看看例子 – Xriuk