简体   繁体   English

Javascript onclick hide div

[英]Javascript onclick hide div

I want to hide this warning div using javascript inside it. 我想用里面的javascript来隐藏这个警告div。

I'm i getting the javascript right? 我正在使用javascript吗? I want to hide/close the div when i click on the close icon (images/close_icon.gif) 当我点击关闭图标时,我想隐藏/关闭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>

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: 要隐藏它你会做一些像:

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 img is in an anchor the onclick event on the anchor is going to fire as well. 另外一件事,因为你的img在一个锚点上,锚点上的onclick事件也会被激活。 As the href is set to # then the page will scroll back to the top of the page. 由于href设置为#,页面将滚动回页面顶部。 Generally it is good practice that if you want a link to do something other than go to its href you should set the onclick event to return false; 一般来说,如果你想要一个链接来做除了转到它的href以外的其他东西你应该设置onclick事件return false;

Simple & Best way: 简单而好的方式:

onclick="parentNode.remove()"

Deletes the complete parent from html 从html中删除完整的父级

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';

}

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'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM