2011-09-01 51 views
0

我有這段代碼(我沒有寫它),它在html文檔中查找<li>類名,然後創建一個基於它的複選框。例如<li class="books"></li> - 該複選框將被標記爲「書籍」。但是,如果您在班級中擁有空間,例如<li class="book case"></li>,則會創建兩個標籤 - 書籍&。我不希望它做到這一點,我想能夠有一個由兩個單詞組成的複選框。在下面的代碼中它說:「現在我有一個空格分隔的所有類名字符串存儲」。我不明白哪一點是這樣做的。任何人都可以看到任何明顯的可以改變,所以這不會發生?在jquery/javascript中停止空格分隔的函數

var stringOfClassNames = ''; 

// grab the class name of each list item to build that string 
$('.filterThis > li').each(function (i) { 
    var thisClassString = $(this).attr('class'); 
    stringOfClassNames = stringOfClassNames +' '+ thisClassString 
}); 

// now i have a space-delimited string of all class names stored 
// in the stringOfClassNames variable. 
// Trim spaces from the ends of that string: 
stringOfClassNames = jQuery.trim(stringOfClassNames); 

// i can't really do anything with it until it's an array, so 
// convert that string to an array. 
var arrayClasses = stringOfClassNames.split(' '); 


// now for the isolating the filter that is common to all. 
// must do before extracting only the unique classes 
// one way to approach: count the number of times classes occur, and 
// if any occur the same number of times as how many list items i have, 
// assume that class is common to all list items, and remove it from 
// the filter list. duplicate class on same item = problem, but 
// i'm not thinking about that right now. 
// i've also chosen sort the pre-unique'd array 
// instead of sorting the unique'd array. i think i have to for the count. 
var arrayClasses = arrayClasses; 
totalNumberOfItemsToFilter = $('.filterThis > li').length; 

存在,如果它是需要更多的代碼...

+0

'stringOfClassNames = stringOfClassNames +」「+ thisClassString'是使您的字符串。 – Jack

回答

0

JavaScript是如何應該知道,這兩個CSS類bookcase應該作爲一個book case字可以治療嗎?空格字符不是CSS類名的有效組成部分,因此您不能將其設置爲「這是一個css類book case」,但將其視爲「這些是其他地方的兩個獨立類book case」。

也許如果您將類更改爲book_case,然後做了一些字符串黑客行爲以替換_

0

你真正的問題是這條線。

stringOfClassNames = stringOfClassNames +' '+ thisClassString 

這將創建一個字符串,它是這樣的:

<li class="one" ></li> 
<li class="two three"></li> 
stringOfClassNames = 'one two three' 

那麼這條線得到由

stringOfClassNames.split(' '); 

分手那麼你真正需要做的僅僅是他們的東西在而不是第一個函數中的數組。

//pseudocode since I think you should learn to program this yourself. Pretty basic. 
var arrayClasses 
$('.filterThis > li').each(function (i) { 
    //get all the class names for this li 
    var thisClassString = $(this).attr('class'); 
    //stick them into an array 
    var splitClasses = thisClassString.split(' '); 
    //now add splitClasses to arrayClasses 
}); 
0
// grab the class name of each list item to build that string 
$('.filterThis > li').each(function (i) { 
    var thisClassString = $(this).attr('class'); 

    // replace all spaces in this element's classes 
    // in order to turn multiple classes into one class 
    thisClassString.replace(/\s/g, ''); 

    stringOfClassNames = stringOfClassNames +' '+ thisClassString 
});