Как мне удалить дефисы в этой строке (сложнее, чем кажется!) - PullRequest
1 голос
/ 20 июня 2011

Прежде всего я должен признаться, что я очень плохо понимаю JS, и это подделанная версия некоторого кода, который я взял в другом месте. По сути, он проходит через набор элементов списка и извлекает их имена классов (которые заполняются CMS, чтобы отразить, например, «Бренд» или «Производитель»), строит их в строку, разбивает строку на массивы и выводит их. Затем он создает список уникальных флажков на основе имени класса, который при выборе или отмене выбора фильтрует элементы списка на странице с помощью jquery.

Моя проблема заключается в том, что, поскольку строка имен классов разделяется на пробел, если значение класса состоит из нескольких слов, значения, заполняющие класс, должны быть дефисированы.

НО ... когда сценарий создает метку для флажка на странице, я задаюсь вопросом, возможно ли удалить дефис без нарушения логики, генерирующей его.

Вот код, который у меня есть, если вы уроните его в файл HTML, вы увидите, как он работает (файл jquery находится в другом месте).

Любая помощь будет принята с благодарностью!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
<head>

<script type="text/javascript" src="http://www.chewbz.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript"> 
/**
 * Removes duplicates in the array 'a'
 */
function unique(a) {
    tmp = new Array(0);
    for(i=0;i<a.length;i++){
        if(!contains(tmp, a[i])){
            tmp.length+=1;
            tmp[tmp.length-1]=a[i];
        }
    }
    return tmp;
}

/**
 * Returns true if 's' is contained in the array 'a'
 */

function contains(a, e) {
    for(j=0;j<a.length;j++)if(a[j]==e)return true;
    return false;
}

$(document).ready(function () {
    // create a string of class names, 
    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
    });

    // Trim spaces from the ends of that string:
    stringOfClassNames = jQuery.trim(stringOfClassNames);

    // convert the string to an array.
    var arrayClasses = stringOfClassNames.split(' ');

    // pull out only unique values from that array
    arrayUniqueClasses = (unique(arrayClasses));

    // we only want to create filters if there are multiple classes
    if (arrayUniqueClasses.length > 1) {

        // create box for filters
        $('<div class="filters" id="filters"><\/div>').insertBefore('.filterThis');

        // create the filter checkboxes based on all the class names
        $.each(arrayUniqueClasses, function() {
            $('<div class="filter-options"><input type="checkbox" checked="checked" value="'+this+'" class="filter-checkbox" id="filterID'+this+'" />'+this+'<\/div>').appendTo('.filters');
        });

        // create a 'show all' checkbox
        $('<div class="filter-options-all"><input type="checkbox" checked="checked" value="filterAll" class="filter-checkbox" id="filterIDall" />Show All<\/div>').appendTo('.filters');

        // create a close button
        $('<img src="" id="filter-close" onClick="document.getElementById(\'filters\').style.display = \'none\'"><\/div>').appendTo('.filters');

        // the filter part
        $('.filters input').click( function() {
            var value= $(this).val();
            if (value == 'filterAll') {
                if ($(this).is(':checked')) {
                    $('.filters input').attr('checked','checked');
                    $('.filterThis li').fadeIn();
                } else {
                    var one=1;
                }
            } else {
                stringValue = '.filterThis > li.'+value;
                if ($(this).is(':checked')) {
                    $(stringValue).fadeIn();
                } else {
                    $(stringValue).fadeOut();
                    $('.filters #filterIDall').removeAttr('checked');
                }
            }
        });
    }
});
</script> 

</head>
<body>

<style>
<!-- 
ul.filterThis {
list-style-type:none;
}
ul.filterThis li {
width:200px;height:200px;background:#eee;border:solid 1px #ccc;float:left;margin:10px;
}
-->
</style>

<ul class="filterThis">

    <li class="Medium-Jars">
        <div class="product-container">
        Medium Jars
        </div>
    </li>

    <li class="Large-Jars">
        <div class="product-container">
        Large Jars
        </div>
    </li>

    <li class="Sweets">
        <div class="product-container">
        Sweets
        </div>
    </li>

    <li class="Medium-Jars">
        <div class="product-container">
        Medium Jars
        </div>
    </li>

    <li class="Sweets">
        <div class="product-container">
        Sweets
        </div>
    </li>

</ul>


</body>

</html>

Ответы [ 2 ]

0 голосов
/ 20 июня 2011

, поскольку строка имен классов разделяется на пробел, если значение класса состоит из нескольких слов, значения, заполняющие класс, должны быть дефисированы.

Могут ли значения, заполняющие класс, использовать подчеркивания вместо пробелов вместо дефисов? (Я не читал код, поэтому извиняюсь, если мое предложение не имеет смысла.)

0 голосов
/ 20 июня 2011

Изменение

// create the filter checkboxes based on all the class names
$.each(arrayUniqueClasses, function() {
   $('<div class="filter-options"><input type="checkbox" checked="checked" value="'+this+'" class="filter-checkbox" id="filterID'+this+'" />'+this+'<\/div>').appendTo('.filters');
});

Для

// create the filter checkboxes based on all the class names
$.each(arrayUniqueClasses, function() {
   $('<div class="filter-options"><input type="checkbox" checked="checked" value="'+this+'" class="filter-checkbox" id="filterID'+this+'" />'+this.replace('-',' ')+'<\/div>').appendTo('.filters');
});

Простой .replace()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...