gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:44:14 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com