JavaScript, как использовать функцию match ()? - PullRequest
0 голосов
/ 19 сентября 2018

У меня проблема с моим кодом JavaScript в поиске слов.Позвольте мне объяснить:

У меня есть такая HTML-страница:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>xPression Reports</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head>  
<body>
<a href="toolbox.cnav.fr"><button>Accueil</button></a>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')">Show all</button>
<button class="btn" onclick="filterSelection('bis')">bis</button>
<button class="btn" onclick="filterSelection('bis.xindd')">bis.xindd</button>
</div>
<div class="container">
<div class=" filterDiv bis" >bis 2017/06</div>
<div class=" filterDiv bis" >bis 2017/07</div>
<div class=" filterDiv bis.xindd" >bis.xindd 2017/06</div>
<div class=" filterDiv bis.xindd" >bis.xindd 2018/01</div>
</div>
<script src="index.js"></script>
</body>
</html>

(я упростила это)

с помощью CSS:

body{
    background-color: #d3d3d3;
}

.container {
    overflow: hidden;
}

.filterDiv {
    float: left;
    color: black;
        border: 1px solid black;
    width: auto;
    text-align: center;
    margin: 2px;
    display: none; /* Hidden by default */
}

/* The "show" class is added to the filtered elements */
.show {
    display: block;
}

/* Style the buttons */
.btn {
  border: none;
  outline: none;
  background-color: #f1f1f1;
  cursor: pointer;
}

/* Add a light grey background on mouse-over */
.btn:hover {
  background-color: #ddd;
}

/* Add a dark background to the active button */
.btn.active {
  background-color: #666;
  color: white;
}

img {
    width:50px;
}

и javascript:

filterSelection("all")
function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("filterDiv");
    if (c == "all") c = "";
  // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].matches(c) > -1) w3AddClass(x[i], "show");
    }
}

// Show filtered elements
function w3AddClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
    //alert(arr1);
  arr2 = name.split(" ");
    //alert(arr2);
  for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {
      element.className += " " + arr2[i];
    }
  }
}

// Hide elements that are not selected
function w3RemoveClass(element, name) {
  var i, arr1, arr2;
 arr1 = element.className.split(" ");
 //alert(arr1);
  arr2 = name.split(" ");
    //alert(arr2);
  for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
  }
  element.className = arr1.join(" ");
}

// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}

Все работает так, как должно быть, чтобы при нажатии на кнопку отображались только кадры, соответствующие этой кнопке.Однако для 6 из них не работают, например, с bis и bis.xindd, я думаю, потому что js берет только «bis» для поиска и поэтому, когда я нажимаю на «bis», отображаются bis и bis.xindd.

И я думаю, что ошибка исходит от этой функции:

filterSelection("all")
function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("filterDiv");
    if (c == "all") c = "";
  // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].matches(c) > -1) w3AddClass(x[i], "show");
    }
}

Я видел информацию о Regex и особенно о функции ma * tch, но я не вижу, как здесь используется

заранее благодарю за помощь

1 Ответ

0 голосов
/ 19 сентября 2018

Рабочее решение для вашего списка фильтров будет выглядеть следующим образом: https://jsfiddle.net/jkrielaars/szagq5hm/31/

Однако: Точки в имени класса не очень хорошая идея.

Вот почему ваш код не работает: On https://developer.mozilla.org/en-US/docs/Web/API/Element/matches указывает, что аргумент должен быть строкой селектора элемента.Наличие точки в вашем имени класса испортит это.

Вам необходимо добавить точку, чтобы указать, что вы имеете дело с классом, однако, поскольку у вас также есть точка в имени класса, у вас будет такой результат: ".bis.xindd".

Если вы видите это как строку селектора, это означает элемент с классами .bis и .xindd.Это не то, к чему вы стремитесь.

Если вы настаиваете на использовании периодов в именах классов, взгляните на .classList.contains ().Ниже вы можете увидеть, как это отличается от .matches ().

var test1 = document.getElementById('test1')
var test2 = document.getElementById('test2')


console.debug('matches does not work without the class period', test1.matches('bis'));
console.debug('matches does not work without the class period', test2.matches('bis.xindd'));
console.debug('matches does work with the class period', test1.matches('.bis'));
console.debug('matches does not work with a class name with a period in it', test2.matches('.bis.xindd'));

console.debug('test1 should contain bis',  test1.classList.contains("bis"));
console.debug('test 2 should contain bis.xindd',  test2.classList.contains("bis.xindd"));


console.debug('test2 should not match with just "bis"',  test2.classList.contains("bis"));
<div id="test1" class="filterDiv bis">bis 2017/06</div>
<div id="test2" class="filterDiv bis.xindd" >bis.xindd 2017/06</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...