如何在我的数组中保存jQuery对象以供以后使用?

时间:2011-08-01 06:53:16

标签: javascript jquery object save

我有一些用户用鼠标挑选的图标。

我有一系列图标,我可以选择和设置边框。我将所选图标的数量限制为5.首先选择的图标将成为黄色边框。接下来的4个将是黑色边框。

在document.ready上,我这样做:

  

$( 'img.selectable')。点击(函数(){       image_click(本); });

对于CSS:

.selectable {
    border: 3px solid #ebe6b3;
    float:left;
    margin:1px;
}

对于HTML:

<img class="selectable" src="img/first_icon.png">

我有这个功能:

function image_click(e)
{
    if($(e).data("clicked")=="yes")
    {
        images_selected--;
        $(e).data("clicked","no").css('border','3px solid ' + NEUTRAL_COLOR);
        if(images_selected==1)
        {
          $('img.selectable').not( e ).filter(function() {
                    return $( this ).data("clicked")=="yes";
                     }).css('border','3px solid ' + YELLOW_COLOR);

        }
    }
    else
    {
        if (images_selected<5)
        {
            images_selected++;
            if(images_selected==1)
            {
                $(e).data("clicked","yes").css('border','3px solid ' YELLOW_COLOR);
            }
            else
            {
                $(e).data("clicked","yes").css('border','3px solid ' + BLACK_COLOR);
            }
        }
    }
};

必须有一个第一个图标,它始终为黄色。我想用订单数组来做,它存储了对象的顺序。 事情是我似乎无法从数组中调用一个对象,仍然保留它的css函数。

我想的是:

var x=[];

image_click(e){..

在某些时候我存储了对象:

    $(e).data("order",clicked_img);

    x[clicked_img]=e;

当我弹出它时:

    alert(x[clicked_img].data("order"));
...}

但.... 好像我再也无法访问数据了。就像当对象离开jQuery领域时,它失去了它的民权。我不知道如何访问它的数据变量。

请帮忙! 谢谢!

2 个答案:

答案 0 :(得分:4)

您保存了DOM元素,而不是jQuery对象。它应该是

x[clicked_img]=$(e);

x[clicked_img]=e;

答案 1 :(得分:2)

  

就像当对象离开jQuery领域时,它已经失去了它的民用   权利。

简单的解决方案:将它放回jQuery领域。你有几个选择:

x[clicked_img] = $(e);
// ...
alert(x[clicked_img].data("order"));

或:

x[clicked_img] = e;
// ...
alert($(x[clicked_img]).data("order"));

或:

x[clicked_img] = e; // assuming e is the DOM element, not the event
// ...
alert(x[clicked_img].dataset.order);

现在不建议使用后者,因为我不确定跨浏览器的含义,但无论如何,这就是你在“常规”JavaScript中的表现。

我建议使用第一种方法,在这种情况下,您还应该在$(e)的开头为image_click分配{{1}},这样每次都不会重建jQuery对象。