简体   繁体   English

如何遍历 JavaScript 循环,所有输出都可用于 DOM

[英]How to iterate through JavaScript for loop with all outputs available to the DOM

I have a function that looks at an array of objects and runs a for loop to iterate through and creates a couple jquery functions.我有一个 function ,它查看一个对象数组并运行一个 for 循环来迭代并创建几个 jquery 函数。 Everything is working great, except when it finishes the DOM only sees the last iteration of the for loop.一切都很好,除了当它完成时 DOM 只看到 for 循环的最后一次迭代。 It's printing out buttons on a page and I want each button to display the tooltip that is associated with it so I'm needing each iteration of the for loop to be available.它正在打印页面上的按钮,我希望每个按钮都显示与其关联的工具提示,因此我需要 for 循环的每次迭代都可用。 Any help or tips to clean this up would be great!任何清理它的帮助或提示都会很棒!

$(window).load(function () {
            var i;
            for (i = 1; i <= array.length; i++) {
                (function(){
                var invbuttons = "#invbuttons" + i;
                var tooltip = "#tooltip" + i;
                $(invbuttons).on("mouseover", function () {
                    $(tooltip).css({
                        visibility: "visible",
                        width: "500px"
                    });
                });
                $(invbuttons).on("mouseout", function () {
                    $(tooltip).css({
                        visibility: "hidden",
                        width: "0px"
                    });
                });

            })}
        });

I think there's an easier, more elegant solution.我认为有一个更简单、更优雅的解决方案。

You can set up a class for all those buttons, like .invbuttons .您可以为所有这些按钮设置 class ,例如.invbuttons

Then it's easy to get a list of them with the querySelectorAll javascript method:然后使用querySelectorAll javascript 方法很容易得到它们的列表:

document.querySelectorAll('.invbuttons').forEach(btn => {
    btn.addEventListener('mouseover', onMouseOver)
    btn.addEventListener('mouseout', onMouseOut)
})

Lastly you only have to declare the appropriate methods for each case:最后,您只需为每种情况声明适当的方法:

function onMouseOver() {
    ...
}

function onMouseOut() {
    ...
}

Good luck!祝你好运!

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

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