0

我正在尝试为图片库中的缩略图实现一个名为收藏夹 (id="#favorites") 的 JqueryUI 按钮。该按钮切换收藏夹图标的显示 (span class="fav")。我正在使用 Isotope 作为缩略图布局,它允许排序和过滤。我想要做的是向同位素 DIV(class="item")添加一类“收藏夹”,以便在单击单个缩略图的“收藏夹”图标时过滤图像。我还希望我的收藏夹图标贴在每个标记为收藏夹的拇指上,并且在单击 JqueryUi 按钮后不切换。到目前为止,我能够使图标保持可见并将类添加到同位素 DIV,除了它将类添加到所有 DIV 以及所有最喜欢的图标保持可见。我需要让它只更改特定缩略图的特定 DIV 和最喜欢的图标。我还在学习 jquery,我的代码很简陋,为此目的可能是完全错误的。任何帮助或方向将不胜感激!

这是一个链接:图库 单击“收藏”按钮可切换图标

HTML:

<div class="item">
    <a href="image.jpg" title="Image">
        <img src="image.jpg" width="80" height="80" alt="Image" />
    </a>
    <span class="fav ui-icon ui-icon-heart"></span>
    <div class="title">Image 1</div>
</div>

按钮代码:

// JQuery Ui button setup
$( "#favorites" ).button({
    label: "Fav",
    icons: { primary: "ui-icon-heart" }
});

// initially hides the icon
$('span.fav').hide();

//click function to toggle icon under thumbs
$("#favorites" ).click(function() {
    $('span.fav').slideToggle('slow'); 
    return false;
});

// my attempt at adding a class 'sticky' to icon to make it stay visible as well as add class '.favorites' to '.item' div to set it up for filtering
$("span.fav" ).live('click', function() {
    $('.fav').addClass("sticky");

    $('.fav').each(function ()
    {
        $(this).removeClass("fav");
    });  
    $('.item').each(function ()
    {
        $(this).addClass("favorites");
    });  
    return false;
});

我使用 .live 是因为 Isotope 正在对代码进行动态更改,但这可能不是正确的做法。

4

1 回答 1

1

在我看来,整个问题可能只是对您正在使用的 jQuery 函数的错误理解。

$("span.fav" ).live('click', function() {
    // This adds the 'sticky' class to EVERY html element on the page that matches '.fav'
    // $('.fav').addClass("sticky");
    // Try this:
    $(this).addClass("sticky");

    // This is a similar problem here.  You're getting everything that matches '.fav'
    // and you REALLY want just the current item you clicked on.
    /*
    $('.fav').each(function ()
    {
        $(this).removeClass("fav");
    });
    */
    // Try this instead:
    $(this).removeClass("fav");

    // Again, you don't want every '.item', but just the one related to the favorite
    // that you just clicked
    /*
    $('.item').each(function ()
    {
        $(this).addClass("favorites");
    });
    */
    // Do this instead, using $(this) as the DOM element where you're starting from:
    // First, get to the icon's parent, which is the specific 'div.item' you want
    // and then just add the class to that one
    $(this).parent().addClass('favorites');

    // You really only need return false on stuff like <a> tags to prevent
    // them from doing what they would normally want to, and GO somewhere
    // return false;
});

问题很简单,您需要了解this变量,该变量将引用您正在与之交互的当前对象。在“click()”方法的情况下,指的是被点击的元素。

代码的较短版本是这样的(它也允许删除收藏夹):

$("span.fav").live('click', function() {
  $(this).toggleClass('sticky')
    .toggleClass('fav')
    .parent()
    .toggleClass('favorites');
});

这利用了 jQuery 的链接,允许您在某事上调用一个又一个方法。注意只有一个';' 在函数中:)

(感谢您对您的内容进行格式化和评论。更容易理解和回答!)

于 2011-03-06T19:56:15.767 回答