如何在jquery中检索多个级别的所有子元素的类名? [英] How to retrieve class names of all child elements at multiple level in jquery?
本文介绍了如何在jquery中检索多个级别的所有子元素的类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在多个级别检索子元素的类名。我正在尝试跟随,但它只提供后方子元素的类名。我做错了什么?
I want to retrieve class names of child elements at multiple level. I'm trying following, but it only gives the class names of rear child elements. What am I doing wrong ?
<script type="text/javascript">
$(document).ready(function(){
thisP=$("#myParagraph");
getChildStyles(thisP);
//function
function getChildStyles(thisobj) {
var classNames;
var classNames1;
$(thisobj).children().each(function(){
classNames+=$(this).attr('class');
if($(this).children().length>0) {
classNames1+=getChildStyles($(this));
}
classNames+=classNames1;
});
return classNames;
}
});
</script>
和HTML,
<ul id="myParagraph" class"mainUL">
<li id="LIOne">ksjdfhsdf</li>
<li id="LITwo">skdjfkdsf<span class"span1Class"><span class="span2class"></span>
</span></li>
<li id="LIThree" class="thirdLIClass">edroiutret</li>
</ul>
推荐答案
你可以获得一些快速的名字数组使用 .map()
更简单,就像这样:
You can get a quick array of the names a bit simpler using .map()
, like this:
$(document).ready(function(){
var arrayOfClassNames = $("#myParagraph").find("[class]").map(function() {
return this.className;
}).get();
});
如果你想要一个字符串,你可以做 arrayOfClassNames.join( '')
...或者你想真正使用它。
If you want a string you can just do arrayOfClassNames.join('')
...or however you want to use it really.
这篇关于如何在jquery中检索多个级别的所有子元素的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文