【问题标题】:how to use a loop within a functions parameter and log the result to the console如何在函数参数中使用循环并将结果记录到控制台
【发布时间】:2016-04-16 05:52:45
【问题描述】:

我想要实现的目标是使用jQuery 收集任何HTML 页面的所有CLASS css 样式,然后循环遍历每个classes 并收集heightwidthtopleft 的每个 class,然后我会将其放入 Array 并记录到控制台。

下面是我目前使用代码的位置。我能够收集所有页面classes,但努力循环通过它们给我每个classheightwidthtopleft。下面是代码,任何人都可以指导我正确的方向或可能给出一个如何构建它的例子吗?任何帮助将不胜感激:)

$(document).ready(function() {

    // VARIABLES
    var allClassNames = [];
    var eachClassName = "";

    // GET CLASS NAMES FROM THE HTML PAGE
    $('[class]').each(function eachClassName(){

        $.each($(this).attr('class').split(' '), function(i, className) {
            if (className.length && $.inArray(className, allClassNames) === -1) {
                allClassNames.push(className);
            }
        });

    });

    // GET THE CSS STYLING FOR EACH CLASS
    function getStyleRuleValue(style, selector) {

        for (var i = 0; i < document.styleSheets.length; i++) {
            var mysheet = document.styleSheets[i];
            var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

            for (k = 0; k < allClassNames.length; k++) {
                console.log(allClassNames[k]);
            }

            for (var j = 0; j < myrules.length; j++) {
                if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector) {
                    return myrules[j].style[style];
                }
            }
        }

    };

    // I'M TRYING TO LOOP THROUGH THE CLASSES WHERE IT SAYS .TWO??
    console.log( getStyleRuleValue('top', '.two') );

});

【问题讨论】:

  • 您知道只需$('.two').css('top') 就可以做到这一点吗?
  • @adeneo 正在为这个问题提供有价值的见解!更好的是,您可以将一组 css 属性名称发送到 jquery,它会为每个属性输出值。这意味着以下工作:$('.two').css(['top', 'left', 'width', 'height'])
  • 非常感谢各位 :) 但如果 HTML 页面上有多个类。我如何能够遍历所有这些,显示值这可行吗? $(allClassNames[k]).css(['top', 'left', 'width', 'height'])
  • $(allClassNames).each(function() {...
  • 我尝试了以下操作,但在控制台中一直未定义,我做错了什么?: $(allClassNames).each(function() { console.log( $(allClassNames[k]). css(['top', 'left', 'width', 'height']) ); });

标签: javascript jquery css loops for-loop


【解决方案1】:

不要混合jQueryJavaScript纯代码,如果你使用jQuery使用它的方法:

HTML 代码:

<div class="div1 value1"></div>
<div class="div1 value2"></div>
<div class="div1 value3"></div>

CSS 代码:

.value1{
  top: 100px;
}

.value2{
  top: 200px;
}

.value3{
  top: 300px;
}

jQuery 代码:

function getStyleRuleValue(style, selector){

    $("." + selector).each(function(){

        console.log( $(this).css(style) );

    }); 

}

getStyleRuleValue("top", "div1");
// 100px
// 200px
// 300px

jsfiddle

编辑:

如果您想将 allClassNames Array 与所有页面类一起使用(您不需要此 Array 来迭代所有页面元素):

var allClassNames = [];

$("[class]").each(function eachClassName(){

    $.each($(this).attr("class").split(" "), function(i, className) {

        if (className.length && $.inArray(className, allClassNames) === -1) {

            allClassNames.push(className);

        }

    });

});

$("." + allClassNames.join(",.")).each(function(){

     console.log( $(this).css(['top', 'left', 'width', 'height']) );

});

jsfiddle

【讨论】:

    【解决方案2】:

    我首先根据样式表构建一个选择器到样式的映射,然后使用它来查找我在文档中找到的每个类。

    function getStyles() {
    
        var allRules = {};
        var selectorIndex = {};
    
        // This will map each individual class to a selector that mentions it
        // i.e. if you have a selector like ".top a", this will create two entries, one for ".top" and
        // one for "a". Each entry will point to the string ".top a", which can then be used to look up
        // the rule in the allRules map.
        var indexSelectors = function (selectorText) {
            if(typeof selectorText === "string" && selectorText.length) {
                $.each(selectorText.split(' '), function (i, sel) {
                    var currentSelectors = selectorIndex[sel];
                    if (typeof currentSelectors === 'undefined') {
                        currentSelectors = [];
                    }
                    currentSelectors.push(selectorText);
                    selectorIndex[sel] = currentSelectors;
                });
            }
        };
    
        // Make a map of all top/left/width/height styles based on the selectors. This will be a "last one
        // wins" map -- later entries will overwrite earlier ones. If you don't want "last one wins," you
        // can use the array.push strategy that the indexSelectors function uses.
        var extractStyles = function (i, rule) {
            indexSelectors(rule.selectorText);
            if(rule.style) {
                var topStyle = rule.style['top'];
                var leftStyle = rule.style['left'];
                var widthStyle = rule.style['width'];
                var heightStyle = rule.style['height'];
                // only make an entry if there's at least one non-empty style in the list we're interested in
                if(topStyle.length || leftStyle.length || widthStyle.length || heightStyle.length) {
                    allRules[rule.selectorText] = {
                        top: rule.style['top'],
                        left: rule.style['left'],
                        width: rule.style['width'],
                        height: rule.style['height']
                    }
                }
            }
        };
    
        var extractFromStyleSheet = function (i, styleSheet) {
            var rules;
            if (styleSheet) {
                rules = styleSheet.cssRules ? styleSheet.cssRules : styleSheet.rules;
                if (rules !== null) {
                    $.each(rules, extractStyles);
                }
            }
        };
    
        // build allRules dictionary
        $(document.styleSheets).each(extractFromStyleSheet);
    
        $('[class]').each(function eachClassName(){
            $.each($(this).attr('class').split(' '),function(i,className) {
                if (typeof className === 'string' && className.length) {
                    className = '.' + className;
                    var selectors = selectorIndex[className];
                    if (selectors) {
                        $.each(selectors, function (i, sel) {
                            var found = allRules[sel];
                            if (found) {
                                console.log(className, sel, found);
                            }
                        });
                    }
                }
            });
        });
    }
    

    我不确定我是否完全理解您在此处尝试执行的操作,尤其是您希望如何处理这样的 CSS 样式?

    .two {
        top: 12px;
    }
    
    .two a {
        top: 24px;
    }
    

    不过,上面的代码应该可以帮助您入门(假设我已经正确理解了您要查找的内容)。

    【讨论】:

      猜你喜欢
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 2018-04-09
      • 1970-01-01
      • 2018-03-10
      • 2018-10-01
      相关资源
      最近更新 更多