【问题标题】:Add hover to a .live('click', function ()将悬停添加到 .live('click', function ()
【发布时间】:2012-12-30 13:31:01
【问题描述】:

此功能显示 arrow-img-down(“显示”图标)。当我点击它打开滑动 div 然后 img 变成 arrow-img-up (一个“隐藏”图标)

我想在此 img 中添加替换 .src 功能,并将鼠标悬停在当前 img 上,如下所示:

$(".showhide").live('click', function () {
    if ($(this).attr("class") == "showhide") {
        this.src = this.src.replace("img/show_btn.png", "img/hide_btn.png");}
         else {
             this.src = this.src.replace("img/hide_btn.png", "img/show_btn.png");}

    $(this).toggleClass("img/show_btn.png");
});

如何添加?

【问题讨论】:

  • 最好使用hasClass 而不是if ($(this).attr("class") == "showhide") {
  • 请注意,应该使用hasClass 的主要原因是因为如果向元素添加第二个类,$(this).attr("class") == … 将不起作用。
  • jquery 网站说 live 已被弃用,应该改用 on。 api.jquery.com/on

标签: jquery


【解决方案1】:

这是您的代码的改进版本:

$( document ).on( 'click mouseenter mouseleave', '.showhide', function () {
    if ( $( this ).hasClass( 'showhide' ) ) {
        this.src = this.src.replace( 'img/show_btn.png', 'img/hide_btn.png' );
    } else {
        this.src = this.src.replace( 'img/hide_btn.png', 'img/show_btn.png' );
    }
} );

【讨论】:

    【解决方案2】:
    $('.showhide').on('click hover', function (e) {
        // Your code here
        // Inside here you can use e.type to find out whether it was a
        // "click", "hover", "mouseup", etc...
    });
    

    您可以使用.bind.live 代替.on。最好使用.on,因为.live.bind 正在贬值。

    【讨论】:

      【解决方案3】:

      添加悬停词。

      $(".showhide").live('click hover', function () {
          if ($(this).attr("class") == "showhide") {
              this.src = this.src.replace("img/show_btn.png", "img/hide_btn.png");}
               else {
                   this.src = this.src.replace("img/hide_btn.png", "img/show_btn.png");}
      
          $(this).toggleClass("img/show_btn.png");
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-09
        • 2016-11-02
        • 1970-01-01
        相关资源
        最近更新 更多