【问题标题】:For loop repeats each loop onto the nextFor 循环将每个循环重复到下一个循环
【发布时间】:2021-08-27 00:38:16
【问题描述】:

我正在尝试使用循环动态调整document.getElementById(divID)。这似乎工作......排序

它一直在循环,如下面的屏幕截图所示。

let searchresult = function(response) {
    let output ="";
    for (let j = 0; j < response.length; j++) {
        let divID = response[j].resortcode + 'results';
        let container = document.getElementById(divID);

        output +=
            `
            <div class="${response[j].resortcode} ${response[j].roomcode}">
            </div>
            `;
        console.log(container);
        $(container).html(output);
    }
};

我将容器 div 设置为 response[j].resortcode,但我认为通过使用 document.getElementById(divID),它只允许在具有相应 resortcode 的 div 中使用该度假村代码 请注意,它还不止一次地循环getElementByID

我希望输出到我的 html 文件中的预制 div id(它确实如此,它只是不断重复)。然后将结果&lt;div class=${response[j].resortcode}"&gt;&lt;/div&gt; 循环到相应的预制 div 中。这是所需结果的 Photoshop 版本:

编辑:添加原始响应的控制台。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript html function loops output


    【解决方案1】:

    您的变量 output 会在每次迭代时添加并且永远不会重置,因此当您将 html 设置为 output 时,它包含之前的每次迭代。

    您可以通过获取 innerHTML 并添加到而不是使用 output 变量来解决此问题。

    您还可以将resortcode 存储到Set (a special kind of array that does not allow duplication of elements) 中,然后在最后将console.log 存储在这些容器中。

    let searchresult = function(response) {
        let resortCodes = new Set();
        for (let j = 0; j < response.length; j++) {
            resortCodes.add(response[j].resortcode); // add only happens if the resortcode isn't already in resortCodes
            let divID = response[j].resortcode + 'results';
            let container = document.getElementById(divID);
    
            container.innerHTML += `
                <div class="${response[j].resortcode}">
                <div class="roominfo"><p class="roomtitle"> ${response[j].roomname} - ${response[j].viewname}</p>
                </div>
                </div>
                `;
        }
    
        resortCodes.forEach(function (resortCode) {
            console.log(document.getElementById(resortCode + "results"));
        };
    };
    

    【讨论】:

    • 我试过这个,但它会停止度假村循环中的每个房间。我已经编辑了我的问题,希望能澄清一些事情。但是,当我在我的 for 循环中移动输出时,它只会在每个度假村占据 1 个房间,然后循环通过它。
    • @BunsenHoneydew 重读您的问题后,我想我找到了您想要的。现在编辑我的答案(可能需要一段时间)
    • @BunsenHoneydew 我已经完成了,请检查修改后的答案
    • 要清除所有结果容器,首先需要更改一些内容:将格式从RESCODEresults 更改为results-RESCODESSRresults 更改为results-SSR)。这样,您可以使用特殊的选择器来选择每个具有以results-div[class^="results-"], div[class*=" results-"] 开头的类的 div。 您还必须更改我的答案中的一些代码才能更改为新格式。然后,您可以创建一个清除所有结果容器的函数。有关示例,请参阅jsfiddle.net/msqgejra。 (基于stackoverflow.com/a/5110337/12101554
    • 我明白了!我将onclick="clearAllResults" 附加到触发我的ajax 请求的搜索按钮上。这似乎有效...再次感谢您,您是救生员。
    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多