比较select.val()和span.text()后产生错误结果

Wrong result after compare select.val() and span.text()

本文关键字:结果 错误 span select val 比较 text      更新时间:2023-09-26

我有以下问题:
点击按钮Filter,我想要获得所选城市的条目。
所以禁止我写大的代码,所以我只显示div与数据。如果你愿意的话,你可以在选项中添加select。
(Select id = "cityFilter" , options: Dnepr, Kharkiv, Lviv)

:

<div id="data">
    <div>
        <a class="userEmail" href="#">user1@domain.ua </a>
        <span> user1 </span>
        <span> Dnepr </span>
        <span><input type = "button" value = "x" /></span>
    </div>
    <div>
        <a class="userEmail" href="#">user2@domain.ua </a>
        <span> user2 </span>
        <span> Kharkiv </span>
        <span><input type = "button" value = "x" /></span>
    </div>
    <div>
        <a class="userEmail" href="#"> user3@domain.ua </a>
        <span> user3 </span>
        <span> Lviv </span>
        <span><input type = "button" value = "x" /></span>
    </div>
    <div>
        <a class="userEmail" href="#"> user4@domain.ua </a>
        <span> user4 </span>
        <span> Dnepr </span>
        <span><input type = "button" value = "x" /></span>
    </div>
    <div>
        <a class="userEmail" href="#"> user5@domain.ua </a>
        <span> user5 </span>
        <span> Lviv </span>
        <span><input type = "button" value = "x" /></span>
    </div>
</div>

cityFilter.js(注释中的代码描述):

$(function() {
  //click on button
  $('body > input').on('click', function() {
    //get selected value
    var cityFilter = $('#cityFilter').val();
    //sort out spans which contains city names
    $('#data > div > a + span + span').each(function() {
      //for check the received value
      console.log($(this).text());
      //compare selected value and span text
      if ($(this).text() != cityFilter) {
        console.log('true');
      }
    });
  });
});

我得到了所有的true

你的span有前后空格

" abc " != "abc"

试试下面的命令:

 if ($(this).text().trim() != cityFilter) {
    console.log('true');
  }