[英]Click HTML element A and add Class on B with pure JavaScript
I can't see what I'm doing wrong here.. Can anyone help please? 我在这里看不到我在做什么。.有人可以帮忙吗?
JavaScript: JavaScript:
function toggleMainNav() {
var navLink = document.getElementsByClassName('nav_link')[0];
var mainNav = navLink.nextSibling;
if ( mainNav.className.match(/(?:^|\s)inactive(?!\S)/) ){
mainNav.className = 'active';
} else{
mainNav.className = 'inactive';
}
}
document.getElementsByClassName('nav_link')[0].addEventListener( 'click' , toggleMainNav );
this is the HTML: 这是HTML:
<a class="nav_link">☰ Menu</a>
<ul class="inactive">
</ul>
nextSibling
will be a text node containing whitespace. nextSibling
将是一个包含空格的文本节点。 Either scan until you get nodeType === 1
or use nextElementSibling
(but check whether it's supported on your target browsers). 扫描直到获得
nodeType === 1
或使用nextElementSibling
(但请检查目标浏览器是否支持它)。
Side note: getElementsByClassName
has worse support than querySelector
/ querySelectorAall
(IE8 has the latter but not the former, for instance), so you might consider using those instead. 旁注:
getElementsByClassName
支持比querySelector
/ querySelectorAall
差(例如,IE8具有后者,但没有前者),因此您可以考虑改用那些。
Side note 2: IE8 also doesn't have addEventListener
. 旁注2:IE8也没有
addEventListener
。
Side note 3: If you hook up your handler via addEventListener
, within the handler this
will already be the first nav_link
, so you don't have to look it up again. 附注3:如果你通过挂钩处理程序
addEventListener
,在处理程序中this
会已经是第nav_link
,这样你就不必再关注一下吧。
Side note 4: Some older browsers will fail if you don't give the third argument to addEventListener
(it didn't used to be optional). 旁注4:如果您不给
addEventListener
第三个参数(以前不是可选参数),则某些较旧的浏览器将失败。 To be broadly-compatible, be sure to include the false
at the end. 为了广泛兼容,请确保在末尾包含
false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.