0

在下面的代码中,我在悬停时使用 id="nav-button" 创建一个 console.log,以便我可以检查它是否工作。

    <ul>                        <!-- Main Navigation -->
      <li ><a id="nav-button" href="welcome/about">ABOUT</a></li>
      <li ><a id="nav-button" href="search-listings">SEARCH LISTINGS</a></li>
      <li ><a id="nav-button" href="featured">FEATURED</a></li>
      <li ><a id="nav-button" href="sell-your-home">SELL YOUR HOME</a></li>
      <li ><a id="nav-button" href="welcome/press">PRESS</a></li>
      <li ><a id="nav-button" href="welcome/contact">CONTACT</a></li>
    </ul>

我的 JavaScript 看起来像这样:

$( document ).ready(function() {
    $("#nav-button").hover(
        function(){
            console.log('done');
        });
});

出于某种原因,只有我的第一个链接响应悬停。其他人什么都不做。

4

3 回答 3

1

ID 应该是唯一的,因此您不能让 id="nav-button" 出现多次。您可以做的是将 id 分配给 ul 标签,如下所示

<ul id="nav-buttons">                        <!-- Main Navigation -->
  <li ><a href="welcome/about">ABOUT</a></li>
  <li ><a href="search-listings">SEARCH LISTINGS</a></li>
  <li ><a href="featured">FEATURED</a></li>
  <li ><a href="sell-your-home">SELL YOUR HOME</a></li>
  <li ><a href="welcome/press">PRESS</a></li>
  <li ><a href="welcome/contact">CONTACT</a></li>
</ul>

然后,您可以将它们称为“#nav-buttons a”

$( document ).ready(function() {
    $("#nav-buttons a").hover(
        function(){
            console.log('done');
    });
});
于 2013-08-19T21:41:41.740 回答
1

Can't have more than 1 item with the same ID, they're not very unique if you do. Change your HTML to:

<ul>                        <!-- Main Navigation -->
  <li ><a class="nav-button" href="welcome/about">ABOUT</a></li>
  <li ><a class="nav-button" href="search-listings">SEARCH LISTINGS</a></li>
  <li ><a class="nav-button" href="featured">FEATURED</a></li>
  <li ><a class="nav-button" href="sell-your-home">SELL YOUR HOME</a></li>
  <li ><a class="nav-button" href="welcome/press">PRESS</a></li>
  <li ><a class="nav-button" href="welcome/contact">CONTACT</a></li>
</ul>

And the JS:

$( document ).ready(function() {
    $(".nav-button").hover(
        function(){
            console.log('done');
        });
});

Here's a fiddle demonstrating it: http://jsfiddle.net/UqyHD/

于 2013-08-19T21:21:56.300 回答
0

Html:

<ul>                       
  <li ><a class="nav-button" href="welcome/about">ABOUT</a></li>
  <li ><a class="nav-button" href="search-listings">SEARCH LISTINGS</a></li>
  <li ><a class="nav-button" href="featured">FEATURED</a></li>
  <li ><a class="nav-button" href="sell-your-home">SELL YOUR HOME</a></li>
  <li ><a class="nav-button" href="welcome/press">PRESS</a></li>
  <li ><a class="nav-button" href="welcome/contact">CONTACT</a></li>
</ul>

Javascript

$( document ).ready(function() {
    $("a.nav-button").hover(
        function(){
            console.log('done');
        });
});

When you find an element by ID it will parse the DOM until it finds the first element with that ID. $("a.nav-button") will select all the elements with that class.

于 2013-08-19T21:25:18.467 回答