javascript - 由于元素中的空间,将数组元素拆分为更多元素

标签 javascript jquery html css

http://jsfiddle.net/rfnslyr/Zxav9/1/

我想输入一段 HTML 代码,让它提取所有 CSS 类和 ID,唯一的。问题是,它将以下每一个都视为一个独特的单一类。

<div class="test hello"></div> 
<div class="test hello"></div> 
<div class="test hello bye"></div> 
<div class="test hello bye yes"></div>

这是我的控制台输出:

0:test hello
1:test hello
2:test hello bye
3:test hello bye yes

uniqueNames["test hello", "test hello bye", "test hello bye yes"] 

理想情况下,我的控制台输出应该如下所示:

0:test hello
1:test hello
2:test hello bye
3:test hello bye yes

uniqueNames["test", "hello", "bye", "yes"] 

函数

$(function() {
    $('#submitCode').click(function() {
        var CSS_CLASSES = [];
        var CSS_IDS = [];
        var el = document.createElement( 'div' );
        var text = $("#codeInput").val();
        el.innerHTML = text;       
        var nodes = el.getElementsByTagName('*');

        for(var i = 0; i < nodes.length; i++) {
            var node = nodes[i];
            if(node.id.length > 0) {
                CSS_IDS.push(node.id); 
            }
            if(node.className.length > 0) {
                CSS_CLASSES.push(node.className);   
            }
        }

        var uniqueNames = [];
        $.each(CSS_CLASSES, function(i, el){
            if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
        });     

        console.log(uniqueNames + " --- " + uniqueNames.length);
    });
});

http://jsfiddle.net/rfnslyr/Zxav9/1/

最佳答案

这可以在一行中完成:

CSS_CLASSES.push.apply(CSS_CLASSES, node.className.split(""));

JSFiddle:http://jsfiddle.net/w645W/

基本上,JavaScript 的 apply() 调用 push() 并将参数列表作为数组传递给它以应用于 CSS_CLASSES。 .split("") 方便地为我们提供了一组由空格分隔的术语。

关于javascript - 由于元素中的空间,将数组元素拆分为更多元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23343530/

相关文章:

javascript - 如何获取表内 TouchSpin 的值

javascript - JS-如何在 Mouseout 上更改图像

jquery - Android - Webview 上使用 loadDataWithBaseURL 的 JQUERY 问题

html - 删除顶部和底部填充

javascript - 如何在 D3.js 中垂直包装 SVG 中的文本?

javascript - 对所有 SVG <path> snap.svg 重复代码功能

javascript - jQuery UI 小部件

javascript - jquery隐藏/显示特定的li子元素

javascript - Screeps 获得所有具有特定内存(角色)的 creeps

javascript - c3.js如何将y标签放置在水平条形图中的条形内?