停止jquery/javascript中的空格分隔函数

Stopping space-delimited function in jquery/javascript

本文关键字:空格 分隔 函数 jquery javascript 停止      更新时间:2023-09-26

我有这段代码(我没有写它),它在html文档中查看<li>类名称,然后基于它创建一个复选框。例如<li class="books"></li>—复选框将被标记为"书籍"。然而,如果你在类中有一个空间,例如<li class="book case"></li>,它会创建两个标签- book &的情况。我不想让它这样,我想要一个由两个单词组成的复选框。在下面的代码中,它说"现在我有一个存储的所有类名的空格分隔的字符串"。我不明白是哪一点在起作用。有人能看出有什么明显的可以改变的地方吗?

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;

Javascript应该如何知道两个css类bookcase应该被视为单个book case字?空格字符不是CSS类名的有效组成部分,所以你不能让它在某个地方是"这是一个单独的CSS类book case",而是把它当作"这是两个单独的类book case"。

也许如果你改变类为book_case,然后做一些字符串黑客替换_

你真正的问题是这一行。

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
});
// 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
});