【问题标题】:Compare two lists with comma separated strings if one list contains only one string如果一个列表仅包含一个字符串,则将两个列表与逗号分隔的字符串进行比较
【发布时间】:2021-02-15 10:18:53
【问题描述】:

我想使用以下脚本比较两个字符串列表,它们包含逗号分隔的字符串。如果有相等的字符串,我想创建另一个 html 元素。如果两个字符串列表都有一个以上的字符串,它工作正常。如果一个列表只包含 1 个不带逗号的字符串,则只会应用 else 条件。

示例 1(有效):

字符串列表 1 = test1, test2, test3 ;字符串列表 2 = test1, test2

预期结果:test1、test2

示例 2(失败):

字符串列表 1 = test1, test2, test3 ;字符串列表 2 = test1

预期结果:test1

var checkDiagnoses = "test1, test2, test3"
var splitDiagnosesArray =checkDiagnoses.split(',');
   
$('.addDiagnoses').html($('.addDiagnoses').html().split(', ').map(function(el) {
  if (el.indexOf(splitDiagnosesArray)) {
    return '<span class="diagnosesTags">' + el + '<span class="materialIcon equalDiagnosis materialicons-Materialicon material-icons">star</span></span>'
} else {
    return '<span class="diagnosesTags">' + el + '</span>'
}

}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addDiagnoses">test1</div>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    三个问题:

    • .split(', ').split(',') 不匹配
    • txt.indexOf(array) 绕错了方向
    • txt.indexOf(array) 如果未找到则返回 -1,因此必须与 &gt;=0 进行比较

    Giving(稍作改动使其成为测试平台,例如 div->input / div.html() -> input.val())

    var checkDiagnoses = "test1,test2,test3"
    var splitDiagnosesArray = checkDiagnoses.split(',');
    
    $("#btn").click(function() {
    
      $('#output').html(
        $('.addDiagnoses').val().split(',').map(function(el) {
          el = el.trim();
    
          if (splitDiagnosesArray.indexOf(el) != -1) {
            return '<span class="diagnosesTags">' + el + '*</span>'
          } else {
            return '<span class="diagnosesTags">' + el + '</span>'
          }
        }))
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type='text' class="addDiagnoses" value='test1'></div>
    <br/>
    <button type='button' id='btn'>test</button>
    <hr/>
    <div id="output"></div>

    【讨论】:

      【解决方案2】:
      var checkDiagnoses = "test1, test2, test3"
      var splitDiagnosesArray =checkDiagnoses.split(',').map(s => s.trim())
      
      $('.addDiagnoses').html($('.addDiagnoses').html().split(',').map(function(el) {
          el = el.trim()
          if (splitDiagnosesArray.includes(el)) {
          return '<span class="diagnosesTags">' + el + '<span class="materialIcon equalDiagnosis materialicons-Materialicon material-icons">star</span></span>'
          } else {
          return '<span class="diagnosesTags">' + el + '</span>'
          }
      
      }))
      

      【讨论】:

        猜你喜欢
        • 2011-10-05
        • 1970-01-01
        • 1970-01-01
        • 2020-05-14
        • 2017-04-10
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多