【问题标题】:How to use JavaScript in a loop如何在循环中使用 JavaScript
【发布时间】:2022-01-07 10:34:24
【问题描述】:

我有这个 javascript

<script>
    $(document).ready(function() {
        $('.summernote1').summernote({
            placeholder: 'start typing',
            lang: 'en-GB',
            height: 300, // set editor height
            minHeight: null, // set minimum height of editor
            maxHeight: null, // set maximum height of editor
            focus: true, // set focus to editable area after initializing summernote
            callbacks: {
                onImageUpload: function(files) {
                    for (var i = 0; i < files.length; i++) {
                        send(files[i]);
                    }
                }
            }
        });
    });

    function send(file) {
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                response = JSON.parse(this.responseText);
                const urls = response.url;
                urls.forEach(imgurls);
                function imgurls(item) {
                    $('.summernote1').summernote('insertImage', item);
                }
            }
        };
        var data = new FormData();
        data.append('files[]', file);
        xhttp.open("POST", "/admin/ans-img-upload", true);
        xhttp.send(data);
    }

//第二个

  $(document).ready(function() {
            $('.summernote2').summernote({
                placeholder: 'start typing',
                lang: 'en-GB',
                height: 300, // set editor height
                minHeight: null, // set minimum height of editor
                maxHeight: null, // set maximum height of editor
                focus: true, // set focus to editable area after initializing summernote
                callbacks: {
                    onImageUpload: function(files) {
                        for (var i = 0; i < files.length; i++) {
                            send(files[i]);
                        }
                    }
                }
            });
        });
    
        function send(file) {
            var xhttp;
            xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    response = JSON.parse(this.responseText);
                    const urls = response.url;
                    urls.forEach(imgurls);
                    function imgurls(item) {
                        $('.summernote2').summernote('insertImage', item);
                    }
                }
            };
            var data = new FormData();
            data.append('files[]', file);
            xhttp.open("POST", "/admin/ans-img-upload", true);
            xhttp.send(data);
        }
    </script>

然后我有这个 html 代码

  <textarea class="form-control summernote1" id="summernote1" name="af_options[]"></textarea>

  <textarea class="form-control summernote2" id="summernote2" name="af_options[]"></textarea>

现在如果我想在summernote1上传图片,图片会被插入到summernote2的最后一个textarea中。

请问我该如何解决这个问题,无论如何我可以在所有 textarea 中使用 1 个 javascript 代码而不是重复 javascript 代码,因为我有一个循环多个 textarea 的 foreach。

请帮忙

感谢您的解决方案....

现在如何追加更多字段...我有下面的代码,但它不适用于图像插入

function add_more_additional_field() {

        $('#additional_options').append(
            '<textarea class="summernote" id="summernote" name="af_options[]" placeholder="Start typing the answers here"></textarea>'
        );

        $(document).ready(function() {
            $([...document.querySelectorAll('#additional_options .summernote')].pop()).summernote();
        });

    }

 

【问题讨论】:

标签: javascript function loops foreach summernote


【解决方案1】:

您可以将所有类名更改为summernote 并使用$('.summernote') 将它们全部选中并应用summernote()

棘手的部分是存储$(this) 并将其传递给send 函数。

$(document).ready(function () {
    $(".summernote").each(function () {
        const self = $(this); // store self as this and this is referenced to each .summernote element.

        self.summernote({
            placeholder: "start typing",
            lang: "en-GB",
            height: 300, // set editor height
            minHeight: null, // set minimum height of editor
            maxHeight: null, // set maximum height of editor
            focus: true, // set focus to editable area after initializing summernote
            callbacks: {
                onImageUpload: function (files) {
                    for (var i = 0; i < files.length; i++) {
                        send(files[i], self); // pass selft to send function
                    }
                },
            },
        });
    });
});

function send(file, context) {
    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            response = JSON.parse(this.responseText);
            const urls = response.url;
            urls.forEach(item => {
                context.summernote("insertImage", item);
            });
        }
    };
    var data = new FormData();
    data.append("files[]", file);
    xhttp.open("POST", "/admin/ans-img-upload", true);
    xhttp.send(data);
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet">


<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>

<textarea class="form-control summernote" id="summernote1" name="af_options[]"></textarea>
<br />
<br />
<textarea class="form-control summernote" id="summernote2" name="af_options[]"></textarea>

【讨论】:

  • 不应该$(".summernote", context) 只是context
  • @phuzi,好地方!你是对的。
  • @ikhvjs 我更新了帖子
  • @phuzi 我更新了问题
  • 请提出一个新问题,而不是扩展原来的问题。
【解决方案2】:

function send(file) 的第二个定义覆盖了第一个。

您应该只定义一个send,并添加第二个参数以包含正确的文本区域。

function send(file, $el) {
    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            response = JSON.parse(this.responseText);
            const urls = response.url;
            urls.forEach(imgurls);
            function imgurls(item) {
                // Use the passed textarea instead of a hard-coded value
                $el.summernote('insertImage', item);
            }
        }
    };
    var data = new FormData();
    data.append('files[]', file);
    xhttp.open("POST", "/admin/ans-img-upload", true);
    xhttp.send(data);
}

要利用这一点,您还需要更新您的 document.ready 回调。您将无法更改 onImageUpload 回调的参数,因此您需要“嵌入”正确的元素。有几种方法可以做到这一点,但我更喜欢在引用正确元素的变量周围创建一个闭包,因为它可以方便以后重构。

$(document).ready(function() {
    $('.summernote1').summernote({
        placeholder: 'start typing',
        lang: 'en-GB',
        height: 300, // set editor height
        minHeight: null, // set minimum height of editor
        maxHeight: null, // set maximum height of editor
        focus: true, // set focus to editable area after initializing summernote
        callbacks: {
            onImageUpload: (() => {
                let $el = $('.summernote1');
                return function(files) {
                    for (var i = 0; i < files.length; i++) {
                        send(files[i], $el);
                    }
                };
           })()
        }
    });
});

这会创建一个围绕$el 形成闭包的IIFE,并在触发onImageUpload 回调时将其传递给send()

您可以为 .summernote2 在其他 document.ready 中为 .summernote2 执行相同的操作

可能需要进行更多重构以进一步减少代码重复。

【讨论】:

  • @UposTyni,你可以查看我的答案,你甚至不需要为每个元素使用let $el = $('.summernote1');
  • @ikhvjs 如何在新的 textarea 中导入功能.... 我使用下面的代码附加它class="summernote" id="summernote" name="af_options[]" placeholder="开始在这里输入答案">'); $(document).ready(function() { $([...document.querySelectorAll('#additional_options .summernote')].pop()).summernote(); }); }`
【解决方案3】:

您有冲突的send() 函数定义。将类添加为参数。

function send(file, summerclass) {
    ...
    function imgurls(item) {
        $(summerclass).summernote('insertImage', item);
        }

并从ready()传递。

send(files[i],'.summernote1');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多