Как проверить текст при переборе цикла элементов - PullRequest
0 голосов
/ 12 декабря 2018

Попытка создать скрипт, который проходит через каждый диапазон, чтобы проверить, содержит ли он: тот же текст, что и элемент h1 страницы.

$(document).ready(function() {
  var partTitle = $("#product_title").text();

  $("span").each(function(i) {
    if ($(this).text().is(":contains('" + partTitle + "')")) {
      $(this).css = ("display", "none");
    } else {

    }

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="page_headers" id="product_title">5/8 Other Stuff</h1>

<label class="radio-option">
 <span>5/8</span> 
</label>

<label class="radio-option">
 <span>1/8</span> 
</label>

<label class="radio-option">
 <span>1/2</span> 
</label>

Codepen:

Ответы [ 4 ]

0 голосов
/ 12 декабря 2018

Используйте .filter(), чтобы сначала сузить коллекцию совпадающих элементов.
Чем применить .css({display: "none"}) к отфильтрованной коллекции

jQuery(function($) {

  var partTitle = $("#product_title").text();

  $(".radio-option span")
    .filter((i, el) => partTitle.includes(el.textContent))
    .css({display: "none"});

});
<h1 class="page_headers" id="product_title">5/8 Other Stuff</h1>
<label class="radio-option"><span>5/8</span></label>
<label class="radio-option"><span>1/8</span></label>
<label class="radio-option"><span>1/2</span></label>

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>

или еще лучше, вместо .css({display: "none"}) используйте некоторые классы CSS Utility , например:

.addClass("u-none");
0 голосов
/ 12 декабря 2018

Если вы хотите проверить, содержит ли строка заголовка текст span в каждом случае, проверьте следующий пример:

$(document).ready(function()
{
    var partTitle = $("#product_title").text();

    $("span").each(function(i)
    {
        if ( partTitle.includes($(this).text()) )
        {
            $(this).fadeOut(2000);
            // Alternatively you can use hide, like on next line.
            // fadeOut() was used because it gives more time to
            // see it working.
            //$(this).hide();
        }
     });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 class="page_headers" id="product_title">5/8 Other Stuff</h1>

<label class="radio-option">
  <span>5/8</span>
</label>

<label class="radio-option">
  <span>1/8</span>
</label>

<label class="radio-option">
  <span>1/2</span>
</label>

Аналогичная логика может быть реализована в случае, если вы хотите проверить, содержит ли текст span текст header:

$(document).ready(function()
{
    var partTitle = $("#product_title").text();

    $("span").each(function(i)
    {
        if ( $(this).text().includes(partTitle) )
        {
            $(this).fadeOut(2000);
            // Alternatively you can use hide, like on next line.
            // fadeOut() was used because it gives more time to
            // see it working.
            //$(this).hide();
        }
     });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 class="page_headers" id="product_title">5/8 Other Stuff</h1>

<label class="radio-option">
  <span>5/8 Other Stuff</span>
</label>

<label class="radio-option">
  <span>1/8</span>
</label>

<label class="radio-option">
  <span>1/2</span>
</label>
0 голосов
/ 12 декабря 2018

Итак, хотите ли вы увидеть, точно ли совпадает текст в интервалах или есть ли в них части, которые находятся в вашем partTitle?

<h1 class="page_headers" id="product_title">5/8 Other Stuff</h1> 
<label class="radio-option">
  <span>5/8</span> 
</label> 
<label class="radio-option">
  <span>1/8</span> 
</label> 

<label class="radio-option">
  <span>1/2</span> 
</label>

Если вы просто проверяете, содержат ли ваши интервалы какой-либо текств partTitle вы можете сделать:

$(document).ready(function() {
 var partTitle = $("#product_title").text();

  $("span").each(function( i ) {
     console.log(partTitle.includes($(this).text()));
     if ($(this).text().includes(partTitle)) {  
      console.log('hi');
      $(this).css = ("display", "none"); 
    } else {

    }

  });
});

console.log содержит информацию о том, как проверить, есть ли у кого-либо из них какой-либо текст в h1, поэтому диапазон 5/8 равен true.

Текущий код в if if проверяет, точно ли совпадает текст диапазона.

0 голосов
/ 12 декабря 2018

Вы можете использовать функцию includes(), например:

$(document).ready(function() {
  var partTitle = $("#product_title").text();

  $("span").each(function(i) {
    if ($(this).text().includes(partTitle)) {
      $(this).css("color", "green");
    } else {
      $(this).css("color", "red");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="page_headers" id="product_title">5/8 Other Stuff</h1>

<label class="radio-option">
  <span>5/8</span> 
</label>

<label class="radio-option">
  <span>5/8 Other Stuff</span> 
</label>

<label class="radio-option">
  <span>1/8</span> 
</label>

<label class="radio-option">
  <span>1/2</span> 
</label>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...