【问题标题】:Can I optimize this jQuery 'toggle' image source function?我可以优化这个 jQuery 'toggle' 图像源功能吗?
【发布时间】:2013-04-26 00:39:45
【问题描述】:

我有这个功能,我不确定是不是最好的。它实际上正在工作。我问是因为我在网上找不到任何“复制粘贴”解决方案,所以我写了这个。没有必要建议其他 CSS 解决方案,我被 <a href><img>text</a> 结构困住了,我无法编写 .css(这一切都是因为后端编码限制/'他们不知所措:lol ')

javascript(一种让客户建立自己的图标集的简单方法[卡在 .png]):

$(".list-habiliy").on({
        mouseenter: function(){
            $('img.icone', this).attr("src",$('img.icone', this).attr("src").replace('.png', '-o.png'));
        },
        mouseleave: function(){
            $('img.icone', this).attr("src",$('img.icone', this).attr("src").replace('-o.png', '.png'));
        }
    },"a");

html(<a> 的列表最多可以包含 30 个元素):

<div class="list-habiliy">
    <a href="some-link1.link"><img class="icone" src="/path/to/default/icons/icon-24px-icon-name1.png" alt="" width="24" height="24" />Some text1</a>
    <a href="some-link2.link"><img class="icone" src="/path/to/default/icons/icon-24px-icon-name2.png" alt="" width="24" height="24" />Some tex2t</a>
    <a href="some-link3.link"><img class="icone" src="/path/to/default/icons/icon-24px-icon-name3.png" alt="" width="24" height="24" />Some text3</a>
    <a href="some-link4.link"><img class="icone" src="/path/to/default/icons/icon-24px-icon-name4.png" alt="" width="24" height="24" />Some text4</a>
</div>

该函数的目标是通过添加/删除图像源中的 '-o' 文本来替换 &lt;a&gt; 中的图标 &lt;img&gt;。我想知道,出于性能原因,我应该使用 .each()、hover() 吗?

jsFiddle:

http://jsfiddle.net/5dpaA/

这是最好的方法吗?

感谢您的所有建议。

[最后]:

由用户 @Xotic750 解释 [已接受答案](我们使用 event 属性并使用 javascript 直接访问元素,而不是在 jquery 中包装它,我们也不会执行任何进一步的 jquery 搜索..)

不知何故,这是我能做的唯一优化。

感谢用户@codelio [我不能接受 2 个答案] 缩短了代码编写:

$(".list-habiliy a").on({
    mouseenter: function (e) {
        var elm=e.delegateTarget.firstChild;
        elm.src=elm.src.replace('.png','-o.png');
    },
    mouseleave: function (e) {
        var elm=e.delegateTarget.firstChild;
        elm.src=elm.src.replace('-o.png','.png');
    }
});

【问题讨论】:

  • 查看 jQuery hover,我认为它更优雅。
  • @rontornambe jQuery.hover() 只是上面代码的简写。
  • 因为在 6 个答案和将近 2 周之后,您可能已经发现其中一个有用,甚至是答案。也许你找到了另一种你现在认为最好的方法。如果您找到了另一种方法,那么最好发布您的答案,嘿,您甚至可以接受自己的答案。否则,这个问题开始看起来像“不是一个真正的问题”。我只是想给你一些反馈,关于 SO 的问题太多了,然后 OP 就再也没有回过头来。 about 中的一些第一行:“Stack Overflow 是一个问答网站”,“这个网站就是为了获得答案。”
  • 谢谢@Xotic750,我明白了。 :)

标签: javascript jquery performance optimization


【解决方案1】:

您拥有它的方式完美无缺,我不能说使用.hover() 会带来任何性能优势,而.each() 是不必要的。事实上:

调用 $(selector).hover(handlerInOut) 是以下的简写: $(selector).on("mouseenter mouseleave", handlerInOut);

【讨论】:

  • 如果我理解:使用 .hover() 只是“漂亮”但不会提高性能?
  • @MilchePatern 使用.hover() 没有性能优势 - 无论如何它最终都会执行.on(),所以它实际上会稍微慢一些,但这样的速度问题可以忽略不计。
【解决方案2】:

我可能会将$('img.icone', this) 查询存储在一个变量中,这样它就不会在每个mouseenter / mouseleave 函数中执行两个查询。

如果将其剪切/粘贴到其他区域,它还可以提高可读性并减少潜在问题:

$(".list-habiliy").on({
    mouseenter: function () {
        var imgIcon = $('img.icone', this);
        imgIcon.attr("src", imgIcon.attr("src").replace('.png', '-o.png'));
    },
    mouseleave: function () {
        var imgIcon = $('img.icone', this);
        imgIcon.attr("src", imgIcon.attr("src").replace('-o.png', '.png'));
    }
}, "a");

JS Fiddle 演示: http://jsfiddle.net/5dpaA/3/

【讨论】:

    【解决方案3】:

    悬停是这样实现的(见here):

    hover: function( fnOver, fnOut ) {
        return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
    }
    

    所以这里没有表现。避免委托会创建大量的处理程序。

    您实际上可以做的是在 html 末尾添加类似这样的内容:

    <div id="hidden-img">
      <img class="icone" src="http://placehold.it/64x64/&text=-o.png1" alt="" width="64" height="64" />
      <img class="icone" src="http://placehold.it/64x64/&text=-o.png2" alt="" width="64" height="64" />
      <img class="icone" src="http://placehold.it/64x64/&text=-o.png3" alt="" width="64" height="64" />
      <img class="icone" src="http://placehold.it/64x64/&text=-o.png4" alt="" width="64" height="64" />
    </div>
    

    并添加一些 CSS:

    #hidden-img {
        margin-left: -9999px;
    }
    

    我认为是 Opera 不会加载隐藏的图像。

    【讨论】:

      【解决方案4】:

      这是另一个解决方案,使用jquery event delegation,因此只有一个事件处理程序(以及 2,一个用于mounseenter,一个用于mouseleave)附加到list-habiliy,如果您有多个这样的结构,那么您可以附加将其更改为document,body,并将选择器更改为list-habiliy a,img。我们没有在 jquery 中包装 this,而是使用 event 属性并使用 javascript 直接访问元素,我们也不会执行任何进一步的 jquery 搜索,因为我们现在假设您的 html 模式不会偏离您拥有的模式表示。尽管如此,由于它是一个用户触发的事件,因此很难衡量它的改进,但它应该比仅使用 jquery 的方法更快。

      HTML

      <div class="list-habiliy">
          <a href="some-link1.link"><img class="icone" src="http://placehold.it/64x64/&text=.png1" alt="" width="64" height="64" />Some text1</a>
          <a href="some-link2.link"><img class="icone" src="http://placehold.it/64x64/&text=.png2" alt="" width="64" height="64" />Some tex2t</a>
          <a href="some-link3.link"><img class="icone" src="http://placehold.it/64x64/&text=.png3" alt="" width="64" height="64" />Some text3</a>
          <a href="some-link4.link"><img class="icone" src="http://placehold.it/64x64/&text=.png4" alt="" width="64" height="64" />Some text4</a>
      </div>
      

      Javascript

      $(".list-habiliy").on("mouseenter", "a,img", function (evt) {
          var target = evt.target;
      
          if (target.nodeName === "IMG") {
              target.src = target.src.replace('.png', '-o.png');
          } else {
              target.firstChild.src = target.firstChild.src.replace('.png', '-o.png');
          }
      }).on("mouseleave", "a,img", function (evt) {
          var target = evt.target;
      
          if (target.nodeName === "IMG") {
              target.src = target.src.replace('-o.png', '.png');
          } else {
              target.firstChild.src = target.firstChild.src.replace('-o.png', '.png');
          }
      })
      

      开启jsfiddle

      【讨论】:

      • 不使用'事件'有一个功能(事件)错误(internetExploser)并且要避免[这是一个javascript保留字]??
      • 它不是 javascript 中的保留字,但至少在某些 Internet Explorer 版本中它是一个全局变量名。我通常写“evt”,不知道为什么我这次没有。我从不使用 IE,所以这对我来说没问题,但我会更改它以避免任何可能的问题。这很有趣,因为 jquery 在他们网站上的许多示例中都使用了它。例如api.jquery.com/on
      • 我也不使用 IE .. 但我们 80% 的客户使用。感谢您的编辑和您对我的要求的考虑。顺便说一句,jQuery 并不完美,到目前为止我见过的任何框架(html、js、css)也不是完美的。
      • +1 ... 事件属性并使用 javascript 直接访问元素,我们也不会执行任何进一步的 jquery 搜索,因为我们现在假设您的 html 模式 ..
      【解决方案5】:

      这总能找到悬停的孩子,也就是你的 img,而且速度很快!

      $(".list-habiliy a").on({
          mouseenter: function (e) {
              //faster is not possible!
              var elm=e.delegateTarget.firstChild, src=elm.src.replace('.png','-o.png');
              elm.src=src;
          },
          mouseleave: function (e) {
              //same a bit jQuery stylish
              var elm=e.delegateTarget.firstChild, src=elm.src;
              $(elm).attr('src',src.replace('-o.png','.png'));
          }
      });
      

      抱歉,有一个较短的。 :)

      $(".list-habiliy a").on({
          mouseenter: function (e) {
              var elm=e.delegateTarget.firstChild;
              elm.src=elm.src.replace('.png','-o.png');
          },
          mouseleave: function (e) {
              var elm=e.delegateTarget.firstChild;
              elm.src=elm.src.replace('-o.png','.png');
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-15
        • 1970-01-01
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 2011-04-25
        • 1970-01-01
        相关资源
        最近更新 更多