jQuery保存局部变量以供稍后在代码中使用

时间:2011-05-30 19:30:59

标签: javascript jquery variables get local

无论如何,我可以保存或访问其功能之外的局部变量吗?请考虑以下代码:

$( "#droppable2" ).droppable({
        activeClass: "ui-state-hover",
        hoverClass: "ui-state-active",
        accept: "#draggable3",
        drop: function( event, ui ) {

            jdc = $(this).attr("id"); //I need to use this value later
            $( this )
                .addClass( "ui-state-highlight" );
                var x = ui.helper.clone();   
                x.appendTo('body');

                var jdi = $("img").attr("id");// I need to use this value later

                $(this).droppable( 'disable' );
        }
    });

无论如何都要获取两个变量的值(上面的jdc和jdi)以供以后在函数外使用吗?

最终目标是获取droppable容器的id和已删除元素的内容。

3 个答案:

答案 0 :(得分:20)

试试这个:

jQuery(element).data(key,value);
// Store arbitrary data associated with the matched elements.

或在函数外声明你的变量。

var example;

function abc(){
   example = "12345";
}

abc();

console.log(example);

答案 1 :(得分:1)

您可以随时将它们存储为元素上的数据:

$(this).data('jdi', $('img').attr('id'));

然后你可以通过另一个调用“.data()”:

从该元素中取回它
var theSavedJdi = $('whatever').data('jdi');

答案 2 :(得分:1)

var jdc;
var jdi;    

$( "#droppable2" ).droppable({
    activeClass: "ui-state-hover",
    hoverClass: "ui-state-active",
    accept: "#draggable3",
    drop: function( event, ui ) {

        jdc = $(this).attr("id"); //I need to use this value later
        $( this )
            .addClass( "ui-state-highlight" );
            var x = ui.helper.clone();   
            x.appendTo('body');

            jdi = $("img").attr("id");// I need to use this value later

            $(this).droppable( 'disable' );
    }
});