简体   繁体   English

Javascript 参数被覆盖

[英]Javascript parameters being overridden

I have code similar to this:我有类似的代码:

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
}

The issue is that when the user clicks on one of the $btn , all the fields in "options" is always the last one of the nested loop (ie when i = imageData.length - 1 and j = sizes.length - 1).问题是,当用户单击$btn ,“选项”中的所有字段始终是嵌套循环的最后一个(即当 i = imageData.length - 1 和 j = size.length - 1 时) . # #

Oddly enough though, the $image passed in is correct!奇怪的是,传入的$image是正确的!

Why is this happening?为什么会这样? How can I fix this issue?我该如何解决这个问题?

In the for loop, 'options' contains the mapping在 for 循环中,'options' 包含映射

preview: $preview, 

meaning that the name stored in 'options' is just 'preview'.这意味着存储在“选项”中的名称只是“预览”。 So you need to access preview as所以你需要访问预览

e.data.options.preview

rather than而不是

e.data.options.$preview

Here is a quick fix that I managed to do:这是我设法做的一个快速修复:

Instead of :代替 :

$btn.on("click", {$image: $image, options: options}, foo);

I did this:我这样做了:

$btn.on("click", {$image: $image, options: $.extend({},options)}, foo);

I believe this make a copy of "options" rather than pass the actual variable.我相信这会复制“选项”而不是传递实际变量。

Better and more detailed answers are welcome!欢迎更好更详细的回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM