我试图将无序列表中的文本与我通过抓取字符串中的内容然后解析它而创建的数组进行比较。我似乎无法让 jQuery 代码的比较部分正常工作,检查字符串是否存在于数组中。有什么建议吗?
HTML
<span id="Subjects">Commercial Law & Contracts, Immigration Law, International Law & Trade, Products Liability</span>
<ul id="SubjectList">
<li>Administrative Law</li>
<li>Agriculture Updates</li>
<li>Alternative Dispute Resolution</li>
<li>Antitrust & Trade Regulation</li>
<li>Commercial Law & Contracts</li>
<li>Immigration Law</li>
<li>International Law & Trade</li>
<li>Products Liability</li>
</ul>
JQuery 代码
var subject_passed = $('#Subjects').text();
var subjectArray = new Array();
subjectArray = subject_passed.split(',');
$('#SubjectList li').each(function(){
if ($.inArray($(this).text(), subjectArray) != -1) {
alert('hello');
}
});
最佳答案
你可以尝试:
var subject_passed = $('#Subjects').text();
//var subjectArray = new Array(); //not really needed as split returns new a array
var subjectArray = subject_passed.split(', '); //add a space to split
$('#SubjectList li').each(function(){
if ($.inArray($(this).text(), subjectArray) !== -1) { //better to use !== for comparison
alert('hello');
}
});
关于javascript - jQuery/Javascript - 从数组中的无序列表中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216424/