问题描述
|
无论如何,我可以在其功能之外保存或访问局部变量吗?考虑下面的代码:
$( \"#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)的值供以后在函数之外使用?
最终目标是获取可放置容器的ID和所放置元素的内容。
解决方法
尝试这个:
jQuery(element).data(key,value);
// Store arbitrary data associated with the matched elements.
或在函数外声明变量。
var example;
function abc(){
example = \"12345\";
}
abc();
console.log(example);
, 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\' );
}
});
, 您总是可以将它们作为数据存储在元素上:
$(this).data(\'jdi\',$(\'img\').attr(\'id\'));
然后,您可以通过再次调用\“。data()\”从该元素取回它:
var theSavedJdi = $(\'whatever\').data(\'jdi\');