【发布时间】:2013-12-27 12:28:13
【问题描述】:
我有多个用于设置或更改图像的按钮。 我环顾四周,看看这样的问题:Update global variable from jquery nested function,但我无法将我发现的内容转化为在这种情况下的相关性。 =/
尝试这样做: 我的按钮可以有两个类中的一个(custom-meta-img-add、custom-meta-img-change)。当我单击一个带有 class -add 的图像时,我正在创建一个图像,如果我单击 -change,我将更新相关图像的 src。
问题:第二次点击按钮,第二次“console.log(button);”显示我点击的第一个按钮。
$('body').on('click', '.custom-meta-img-add, .custom-meta-img-change', function(e){
e.preventDefault();
var button = $(this);
console.log(button);
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
console.log(button);
});
//Open the uploader dialog
custom_uploader.open();
})
您将如何解决这个问题?第一个 console.log(button) 正确地显示了我每次点击的按钮。
【问题讨论】:
-
第二个
console.log(button);位于事件处理程序中,仅在未创建上传器对象时附加,即仅在第一次点击时。因此,它将仅记录您首先单击的按钮。 -
关于如何在每次点击时更改 custom_uploader 中点击的按钮的值的任何想法?我的意思是,有没有一种方法更喜欢在每次点击时创建一个新的上传器?