此代码将隐藏第一个 div,即使它是从第二个按钮激活的。我应该使用什么关键字来隐藏父 div(第一个按钮隐藏第一个 div,第二个按钮隐藏第二个 div)?
var x = document.getElementsbyClassName(myClass);
function myFunction() {
x[0].display = "none";
}
<div class="myClass">
<button onclick="myFunction()">Click</button>
</div>
<div class="myClass">
<button onclick="myFunction()">Click</button>
</div>
最佳答案
无需尝试预测用户将单击哪个元素,只需使用事件监听器即可获取已与之交互的元素并做出适当的响应:
function hide() {
// EventTarget.addEventListener() passes the 'this'
// Node to the function; here 'this' is whichever
// element was clicked:
let target = this;
// here we set the display of the clicked element's
// parentNode to 'none':
target.parentNode.style.display = 'none';
}
// here we use document.querySelectorAll(), which takes
// a CSS selector as an argument and returns an Array-Like
// nodeList of the found elements, which is passed to
// nodeList.forEach():
document.querySelectorAll('.myClass > button').forEach(
// nodeList.forEach() iterates over the supplied nodeList,
// to perform the supplied actions. Here we use an Arrow
// function to perform the required action;
// myClassElement is the current Element of the nodeList over
// which we're iterating.
// In the Arrow function we bind an event-listener to listen
// for a 'click' event, which executes the supplied function
// in response (note the deliberate omission of the parentheses;
// we don't pass 'hide()' (unless you want to bind the result of
// a supplied function):
myClassElement => myClassElement.addEventListener('click', hide)
);
<div class="myClass">
<button>Click</button>
</div>
<div class="myClass">
<button>Click</button>
</div>
在上面的方法中,我使用了一种不显眼的 JavaScript 方法,将事件处理程序从 HTML 移到 JavaScript 中,这对于“漂亮”的 HTML 来说更好,但从代码维护的 Angular 来看也更好:它可以防止您必须在 HTML 中查找所有提到的函数才能删除事件监听器或将它们更新为新函数。
顺便说一句,上面的代码应该位于 <script>
中标签位于文档末尾、结束之前 </body>
标签,或在 <head>
中的就绪事件处理程序中文件的内容;否则,当 JavaScript 在遇到时运行时,当绑定(bind)事件监听器时,您希望将事件绑定(bind)到的元素将不会出现在 DOM 中。
关于javascript - 从 getElementsbyClassName 中选择当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286890/