You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码重构后图片裁剪脚本运行失败,v变量出现未定义报错

问题根因

jQuery的$.each()方法回调函数的参数顺序为先索引/键,后元素/值,你写的回调参数function (v,k)顺序颠倒,此时第一个入参v实际是遍历的索引(数字类型),没有previewer属性,就触发了变量相关报错。

修复方案

把$.each的回调参数顺序调换即可,修复后的完整代码如下:

portada_next.on("click", function () {
    // 若my_coords未提前声明可放开下一行注释,避免隐式全局变量隐患
    // let my_coords;
    if(portada_uploader.isValid && !portada_uploader.isEmpty){
        portada_next.parents(".carousel").carousel("next");
        $.each(portada_uploader.inputs, function (k, v) {
            let img = $(v.previewer.img).clone();
            img.addClass("img-fluid");
            $("#crop").append(img);
            const nw = img.get(0).naturalWidth;
            const nh = img.get(0).naturalHeight;
            img.Jcrop({
                minSize: 0,
                aspectRatio: 2,
                setSelect: [ 0, img.height()/2, nw,nh],
                allowResize: true,
                allowSelect: false,
                trueSize: [nw,nh],
                onChange: function (coords) {
                    my_coords = coords;
                }
            });
        });
    }
});

额外注意点

如果代码中没有提前声明my_coords变量,直接赋值会隐式创建全局变量,可能引发其他上下文冲突,建议在使用前提前用let my_coords声明该变量。

内容的提问来源于stack exchange,提问作者user16311982

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 03:54:10