使用以下脚本,我想比较两个包含逗号分隔字符串的字符串列表。如果有相等的字符串,我想创建另一个html元素。如果两个字符串列表都包含多个字符串,则效果很好。如果一个列表仅包含1个不带逗号的字符串,则仅将应用else条件。
Example1(有效):
字符串列表1 = test1,test2,test3;字符串列表2 = test1,test2
预期结果:test1,test2
Example2(失败):
字符串列表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>
三个问题:
.split(', ')
vs.split(',')
将不匹配txt.indexOf(array)
是错误的方法txt.indexOf(array)
如果未找到则返回-1,因此必须与 >=0
给予(进行一些细微的更改以使其成为测试平台,例如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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句