Контент для второго div не оповещается с помощью $ (this) - PullRequest
0 голосов
/ 20 сентября 2019

Это мой полный код:

<input id="storecipient">
<div class="hidbdsp">
    <div class="hidname">tomato</div>
    <div class="hidname">orange</div>
</div>

<script type="text/javascript">
$(document).ready(function() {
  $("#storecipient").on('input', function() {  
    var thisFstchar = $(this).val();
    var name = $(this).siblings(".hidbdsp").children(".hidname").html();
    if (thisFstchar.charAt(0) == name.charAt(0)) {
        alert(name);
    }
  });
});
</script>

Мой код js предупреждает о полном слове, которое содержит первую букву слова, набранного на входе.Поэтому, когда набирается буква «t», появляется слово «помидор», но когда на входе набирается «o», «оранжевый» не появляется.Несмотря на то, что и "orange", и "tomato" имеют один и тот же класс ".hidname", селектор $ (this) будет выбирать только помидор, но пропускает оранжевый.Почему это?

Ответы [ 4 ]

1 голос
/ 20 сентября 2019

Попробуйте это

$(document).ready(function() {
    $("#storecipient").on('input', function() {
        var thisFstchar = $(this).val();
        $(this).siblings(".hidbdsp").children(".hidname").each(function() {
            var name = $(this).html();
            if (thisFstchar.charAt(0) == name.charAt(0)) {
                alert(name);
            }
        });

    });
});
<input id="storecipient">
<div class="hidbdsp">
    <div class="hidname">tomato</div>
    <div class="hidname">orange</div>
</div>
  
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
1 голос
/ 20 сентября 2019

Как указано @ misner3456, jQuery.html() возвращает HTML только первого соответствующего элемента.Чтобы получить HTML для всех совпадающих элементов, попробуйте что-то вроде зацикливания всех классов и добавления HTML каждого элемента в строку.Например:

let html;

$(".hidname").each(function() {
   html += $(this).html();
});
0 голосов
/ 20 сентября 2019

Чтобы получить всех детей и потомков:

$('.hidbdsp *')

Чтобы получить только прямых детей:

$('.hidbdsp > *')

.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input id="storecipient">
<div class="hidbdsp">
    <div class="hidname">tomato</div>
    <div class="hidname">orange</div>
</div>

<script type="text/javascript">
$(document).ready(function() {
    $("#storecipient").on('input', function() {
        var thisFstchar = $(this).val();
         $('.hidbdsp *').each(function() {
            var name = $(this).html();
            if (thisFstchar.charAt(0) == name.charAt(0)) {
                alert(name);
            }
        });

    });
});
</script>
</body>
</html>
0 голосов
/ 20 сентября 2019

Вы можете выполнить рефакторинг для прямой итерации $(".hidbdsp .hidname").each() вместо поиска родного брата.

$(document).ready(function() {
  $("#storecipient").on('keyup', function() {
    var thisFstchar = $(this).val();
    $(".hidbdsp .hidname").each(function() {
      var name = $(this).html();
      if (thisFstchar.charAt(0) == name.charAt(0)) {
        alert(name);
      }
    });
  });
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input id="storecipient">
<div class="hidbdsp">
  <div class="hidname">tomato</div>
  <div class="hidname">orange</div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...