javascript - 从 getElementsbyClassName 中选择当前元素

标签 javascript html getelementsbyclassname

此代码将隐藏第一个 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/

相关文章:

php - 使用 getElementByClassName,并通过表单携带变量

javascript - 如何告诉 MathJax 对下标使用替代语法?

javascript - JS : checking object with key vs hasOwnProperty?

javascript - 使 querySelector 仅针对单击的此元素?

javascript - 如何使用 JavaScript 获取 ElementByClass 而不是 GetElementById?

JavaScript:为包含特定类的元素分配唯一ID

javascript - 如何将元素放在可嵌套列表中

javascript - jQuery:删除ajax成功添加的类

javascript - 为 input[number] 中的箭头设置默认值

javascript - 获取同级文本输入值