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/