我试图通过它的开始 name
使用该值来查找类名,我正在根据名称的长度寻找不同的长度。
我得到了错误的结果。任何人都可以帮助我找到正确的方法。这是我的作品:
html:
<div id="first">
<span class="textHighLight userNote2">CO</span>
<span class="textHighLight userNote2">N</span>
<span class="textHighLight userNote2">STR</span>
<span class="textHighLight userNote2">U</span>
<span><span class="textHighLight userNote2">CTION</span>,</span>
</div>
<div id="second">
<span class="textHighLight userNote2 userNote3">CO</span>
<span class="textHighLight userNote2 userNote3">N</span>
<span class="textHighLight userNote2 userNote3">STR</span>
<span class="textHighLight userNote2 userNote3">U</span>
<span><span class="textHighLight userNote2 userNote3">CTION</span>,</span>
</div>
var getLength = function (element) {
var classLength = element.find('.textHighLight').filter(function(index){
return this.className.split(' ').reduce(function(cNum, cName){
return cName.substring(0, 8) === 'userNote' ? cNum + 1 : cNum;
}, 0);
}).length;
return classLength;
}
var first = getLength($('#first'));
console.log(first) //returns 5 this is correct.
var second = getLength($('#second'));
console.log(second ) //returns 5 instead 10 (i am looking for 10!)
我明白,我没有按照应有的方式正确过滤。有人帮帮我吗?
最佳答案
此答案使用 jQuery.map
将元素数组转换为数字数组,表示每个元素上有多少个以 userNote
开头的类。然后它使用 Array.reduce
简单地总结这些数字。
var getLength = function (element) {
var classLength = element.find('.textHighLight').map(function(i,e){
return this.className.split(' ').reduce(function(cNum, cName){
return cName.substring(0, 8) === 'userNote' ? cNum + 1 : cNum;
}, 0);
}).get().reduce(function(p,c){
return p+c;
});
return classLength;
}
console.log(getLength($('#first')))
console.log(getLength($('#second')))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first">
<span class="textHighLight userNote2">CO</span>
<span class="textHighLight userNote2">N</span>
<span class="textHighLight userNote2">STR</span>
<span class="textHighLight userNote2">U</span>
<span><span class="textHighLight userNote2">CTION</span>,</span>
</div>
<div id="second">
<span class="textHighLight userNote2 userNote3">CO</span>
<span class="textHighLight userNote2 userNote3">N</span>
<span class="textHighLight userNote2 userNote3">STR</span>
<span class="textHighLight userNote2 userNote3">U</span>
<span><span class="textHighLight userNote2 userNote3">CTION</span>,</span>
</div>
关于javascript - 如何通过起始值查找类名长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28304934/