在Javascript中激活链接

Zei*_*vic 5 javascript css

我有一些Javascript的问题.事实上,我只是那种脚本语言的新手,所以我需要一些帮助.问:如何激活此链接:

<a href="#box1">something</a>
Run Code Online (Sandbox Code Playgroud)

此链接只是链接到位于index.html文件中的div,因此没有页面加载.这是div

<div id="box1" class="box">
<h3><a name="box1">something</a></h3>
</div>
Run Code Online (Sandbox Code Playgroud)

avr*_*mov 3

由于您才刚刚开始,我建议您使用 jQuery 等库。所以,如果你的 HTML 是这样的:

<div id="box1" class="box">
<h3><a name="box1">something</a></h3>
</div>
<div id="box2" class="box">
<h3><a name="box2">something</a></h3>
</div>
<div id="box3" class="box">
<h3><a name="box3">something</a></h3>
</div>
Run Code Online (Sandbox Code Playgroud)

你有一个 CSS 类,名为youarehere

.youarehere { color:white; background:green; }
Run Code Online (Sandbox Code Playgroud)

使用 jQuery,您可以编写如下内容:

$(".box > a").click(function() {             // when clicking any of these links
    $(".box > a").removeClass("youarehere"); // remove highlight from all links
    $(this).addClass("youarehere");          // add highlight to clicked link
})
Run Code Online (Sandbox Code Playgroud)

在普通的 JS 中,需要付出更多的努力才能实现这一点。帮自己一个忙,不要重新发明轮子——人们已经解决了这个问题,所以使用他们的劳动产品让你的生活更轻松。