我有类似的代码:
for (i = 0; i < imageData.length; i++) {
for (j = 0; j < sizes.length; j++){
width = sizes[j][0];
height = sizes[j][1];
objectId = 'cropper-' + i + '-' + j;
var $image = $('#' + cropperId + ' > img'),
$preview = $('#preview_cropper-' + i + '-' + j),
$btn = $('strict-mode_cropper-' + i + '-' + j);
var options = {
...
width: width,
height: height,
$preview: $preview,
...
};
$btn.on("click", {$image: $image, options: options}, foo);
}
}
function foo(e) {
var $image = e.data.$image; // Gives the correct Image
var $preview = e.data.options.$preview // Always the last $preview. Not the one that was passed in!
var width = e.data.options.width //Also incorrect
var height = e.data.options.height //Also incorrect
}
问题是,当用户单击 $btn
之一时,“options”中的所有字段始终是嵌套循环的最后一个字段(即,当 i = imageData.length - 1 和 j = 尺寸.长度 - 1)。 #
奇怪的是,传入的 $image
是正确的!
为什么会发生这种情况?我该如何解决这个问题?
最佳答案
在 for 循环中,“选项”包含映射
preview: $preview,
意味着存储在“选项”中的名称只是“预览”。所以你需要访问预览为
e.data.options.preview
而不是
e.data.options.$preview
关于Javascript 参数被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29373980/