我在一个jQuery函数上遇到了范围(我认为)的问题,该函数在wordpress中打开了一个媒体上传窗口。
我有一个在多个按钮上使用的功能,但我需要在返回结果时参考特定按钮。看看我的代码:
var file_frame;
jQuery('.bjqs_upload_button').live('click', function( event ){
event.preventDefault();
current_id = $(this).attr('id');
[...]
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
// Set the thumbnail on page to the image just selected
$("#". current_id).parent().find('img').attr("src", attachment.url);
});
...
});
在上面的代码中,我使用代码
收集了当前按钮的idcurrent_id = $(this).attr('id');
然后我试着稍后在file_frame.on()函数中引用它。
$("#". current_id).parent().find('img').attr("src", attachment.url);
我得到了一个不受欢迎的'在此时运行警报。
我试图将变量传递给像这样的函数
file_frame.on( 'select', function(current_id) {
但问题仍然存在。
如果可能的话,会对此有所帮助。
由于
答案 0 :(得分:0)
所以我最终使用了全局变量(我试图最初避免使用它。
将变量设置为
window.current_id = $(this).attr('id');
并在函数中调用它:
$("#" + window.current_id).parent().find('img').attr("src", attachment.url);