Javascript onclick 隐藏 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5515527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:34:00  来源:igfitidea点击:

Javascript onclick hide div

javascript

提问by karto

I want to hide this warning div using javascript inside it.

我想在其中使用 javascript 隐藏此警告 div。

I'm i getting the javascript right? I want to hide/close the div when i click on the close icon (images/close_icon.gif)

我对 javascript 的理解正确吗?我想在单击关闭图标时隐藏/关闭 div (images/close_icon.gif)

<div>
  <strong>Warning:</strong>
  These are new products
  <a href='#' class='close_notification' title='Click to Close'>
    <img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="this.close" />
  </a
</div>

回答by Coin_op

If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like:

如果您想关闭它,您可以将其隐藏或从页面中删除。要隐藏它,您可以执行一些 javascript,例如:

this.parentNode.style.display = 'none';

To remove it you use removeChild

要删除它,您使用 removeChild

this.parentNode.parentNode.removeChild(this.parentNode);

If you had a library like jQuery included then hiding or removing the div would be slightly easier:

如果你有一个像 jQuery 这样的库,那么隐藏或删除 div 会稍微容易一些:

$(this).parent().hide();
$(this).parent().remove();

One other thing, as your imgis in an anchor the onclick event on the anchor is going to fire as well. As the hrefis set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its hrefyou should set the onclick event to return false;

另一件事,当您img处于锚点时,锚点上的 onclick 事件也将触发。当href设置为# 时,页面将滚动回页面顶部。一般来说,如果你想让一个链接做一些不是去它的事情,href你应该将 onclick 事件设置为return false;

回答by Amir Savand

Simple & Best way:

简单和最好的方法:

onclick="parentNode.remove()"

Deletes the complete parent from html

从 html 中删除完整的父级

回答by Chris Sobolewski

HTML

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

回答by Andrei

just add onclick handler for anchor tag

只需为锚标记添加 onclick 处理程序

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

或更改 img 标签的 onclick 处理程序

onclick="this.parentNode.parentNode.style.display = 'none'"