[英]Changing a page element's style with javascript using the <a> tag and onclick?
I have a div block 我有一个div块
<div id='block'> <a href="#" onclick="Document.getElementById('block').style = 'display: none;';">Hide</a> </div>
and I want to be have a link that will hide the block when clicked, I tried the above but it doesn't work I'm not sure how to get this to work, any ideas or guidance? 并且我想拥有一个链接,该链接将在单击时隐藏该框,我尝试了上述操作,但它不起作用,我不确定如何使它起作用,是否有任何想法或指导?
style
is an object which properties are assigned directly. style
是直接分配属性的对象。 It's not like the HTML attribute. 它不像HTML属性。 So what you want is: 所以您想要的是:
document.getElementById('block').style.display = 'none';
<div id='block'> <a href="#" onclick="Document.getElementById('block').style.display = 'none';">Hide</a> </div>
...or with some help from jquery: ...或在jquery的帮助下:
$('#block').hide();
// or:
$('#block').css('display','none');
It is better to put the javascript in the <head>
or better yet a separate file not the HTML. 最好将javascript放在<head>
或者最好将HTML放在一个单独的文件中。 But since you have it in the HTML you could shorten your code to onclick="this.parentNode.style.display='none';"
但是,由于您将其包含在HTML中,因此可以将代码缩短为onclick="this.parentNode.style.display='none';"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.