【问题标题】:jQuery img.src reset after click点击后 jQuery img.src 重置
【发布时间】:2012-06-05 17:45:08
【问题描述】:

我的导航有问题。

HTML

<ul id="menu_bar">
    <li><a href="#home" class="hov selected"><img src="img/Home_on.png" alt="Home" />Home</a></li>
    <li><a href="#portfolio" class="hov"><img src="img/Portfolio_off.png" alt="Portfolio" />Portfolio</a></li>
    <li><a href="#about" class="hov"><img src="img/About_off.png" alt="About" />About</a></li>
   <li><a href="#contact" class="hov"><img src="img/Contact_off.png" alt="Contact" />Contact</a></li>
</ul>

JS

$(document).ready(function() {
    $("img.roll").hover(
        function() { this.src = this.src.replace("_off", "_over");},
        function() { this.src = this.src.replace("_over", "_off");}
    );
    $("a.hov").hover(
        function() {
            var img = $(this).find("img")[0];
            img.src = img.src.replace("_off", "_over");},
        function() {
            var img = $(this).find("img")[0];
            img.src = img.src.replace("_over", "_off");}
    );
    $("a.hov").click(
        function() {
            var img = $(this).find("img")[0];
            img.src = img.src.replace("_over", "_on");
            $("a.hov").removeClass("selected");
            $(this).addClass("selected");
        }
    );

});

我想创建一个点击函数来改变锚类,改变这个锚内部的 img src,当我在另一个锚上使用它时,它会将最后点击的锚重置为普通类和普通 img src。 现在我的函数从所有“a.hov”中删除类,但没有将所有这些项目的 img.src 更改为“_off”,并且不知道如何制作。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:
    $("a.hov").click(
            function() {
    
                $("a.hov").each( //Change all "_over" to "_off" for all items
                 function() {
                     var img = $(this).find("img")[0];
                     img.src = img.src.replace("_over", "_off");
                 });
    
                var img = $(this).find("img")[0];
                img.src = img.src.replace("_over", "_on"); //replace all "_over" (mabe all will work without this line)
                img.src = img.src.replace("_off", "_on"); //replace "_off"
    
                $("a.hov").removeClass("selected");
                $(this).addClass("selected");
            }
        );
    

    【讨论】:

      【解决方案2】:
      $("a.hov").click(
              function() {
                  var img = $('img', this);
                  console.log(img)
                  img.attr('src', img.attr('src').replace("_off", "_on"));
                  $('a.hov').removeClass("selected");
                  $(this).addClass("selected");
              }
          );
      

      【讨论】:

      • 但这不是从selected 类中删除,然后将其添加回相同的$(this) 元素吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2012-05-17
      • 2011-01-08
      • 1970-01-01
      相关资源
      最近更新 更多