如何解决jQuery保存局部变量以供稍后在代码中使用
| 无论如何,我可以在其功能之外保存或访问局部变量吗?考虑下面的代码:$( \"#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\');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。