Javascript jQuery 保存局部变量以供稍后在代码中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6180077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery save local variable for use later on in the code
提问by Sol
Is there anyway that I can save or access a local variable outside of it's function? Consider the code below:
无论如何,我可以在其函数之外保存或访问局部变量吗?考虑下面的代码:
$( "#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' );
}
});
Is there anyway to get the values of the two variables (jdc and jdi above) for later use outside of the function?
有没有办法获取两个变量(上面的 jdc 和 jdi)的值以供以后在函数之外使用?
The ultimate goal is to get id of droppable container and content of dropped element.
最终目标是获取可放置容器的 id 和放置元素的内容。
回答by Thomas
try this:
尝试这个:
jQuery(element).data(key,value);
// Store arbitrary data associated with the matched elements.
or declare your variable outside the function.
或者在函数外声明你的变量。
var example;
function abc(){
example = "12345";
}
abc();
console.log(example);
回答by Pointy
You could always just store them as data on the element:
您始终可以将它们存储为元素上的数据:
$(this).data('jdi', $('img').attr('id'));
Then you can get it back from that element with another call to ".data()":
然后你可以通过另一个调用“.data()”从那个元素取回它:
var theSavedJdi = $('whatever').data('jdi');
回答by kei
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' );
}
});