我试着在点击元素HomeNav下的导航栏中的第二个li时显示警报。您可以在codepen上签出完整的代码
var linkButton = document.getElementById('#homenav li:nth-child(2) a');
if(linkButton) {
linkButton.addEventListener('click', function() {
alert('Test');
});
}
HTML
<div id="homenav">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav"></ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">Table Ranking</a>
</li>
<li>
<a href="#">Blog</a>
</li>
</ul>
</div>
</div>
</div>
</div>
文档#GetElementById
使用要定位的元素的ID
。
如果要使用选择器
,请尝试文档#queryselector
:
null
const linkButton = document.querySelector('#homenav li:nth-child(2) a');
if(linkButton) {
linkButton.addEventListener('click', function() {
alert('Test');
});
}
<div id="homenav">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav"></ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
<li><a href="#">Table Ranking</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>
</div>
</div>
</div>