我可以改进此JQuery图像替换代码吗? [英] Can I improve this JQuery image replace code?

查看:96
本文介绍了我可以改进此JQuery图像替换代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML看起来像:

<dl>
  <dt>
    <img src='Images\Something\expand-close.gif' /> Something 1
  </dt>
  <dd>Something 1 Text</dd>
</dl>

此HTML重复了1次或更多次,因此同一页面上可能有许多HTML实例.

This HTML is repeated 1 or more times so there could be many instances of the HTML on the same page.

我用来扩展dd并替换图像的Jquery是:

The Jquery I am using to expand the dd and replace the image is:

$("dl").find("dt").click(function() {
  // toggle the dd
  $(this).next().toggle(200);

  // replace the expand / close image
  var img = $(this).find("img");
  var src = img.attr("src");
  if (src.lastIndexOf("open.gif") != -1)
  {
    img.attr("src", src.replace("open.gif", "closed.gif"));
  }
  else
  {
    img.attr("src", src.replace("closed.gif", "open.gif"));
  }
});

这一切工作正常,完全可以满足我的需要.我的问题是,能否将JQuery函数做得更好?我对使用JQuery还是比较陌生,这是我摘录的一小段.如果可以做得更好,请在我试图学习如何编写更好的JQuery代码时解释这些更改.任何其他指针或建议也将不胜感激.

This all works fine and does exactly what I need it to do. My question is, can the JQuery function be done better? I am relatively new to using JQuery and this one was a snippet I rattled off. If it could be done better, please explain the changes as I am trying to learn how to write better JQuery code. Any other pointers or suggestions would be appreciated as well.

推荐答案

非常接近.试试:

$("dl > dt").click(function() {
  var dd = $(this).next();
  if (dd.is(":visible")) {
    var newimage = "closed.gif";
    dd.hide(200);
  } else {
    var newimage = "open.gif";
    dd.show(200);
  }
  var img = $(this).find("img");
  img.attr("src", img.attr("src").replace(/(open|closed)\.gif$/, newimage);
});

区别是:

  1. 在这种情况下,只需使用"dl> dt"(或"dl dt")即可;
  2. 这段代码着眼于事物是否可见,而不是src图像,这可能会导致不同步,特别是在存在延迟的情况下;
  3. 最后一行的正则表达式只是用正确的内容代替存在的内容,以应对不正常的情况.

这篇关于我可以改进此JQuery图像替换代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆