0

我试图将无序列表中的文本与我通过抓取字符串中的内容然后解析它创建的数组进行比较。我似乎无法让我的 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');
    }
});
4

3 回答 3

1

你可以试试:

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');
   }
});
于 2012-06-26T21:51:01.293 回答
1

您应该使用$.trim()在拆分后和比较期间从文本值中删除外部空格:

var subject_passed = $('#Subjects').text();
var subjectArray = subject_passed.split(','); 
$.each(subjectArray, function(i, el){
    subjectArray[i] = $.trim(el);
});

$('#SubjectList li').each(function(){  
    if ($.inArray($.trim($(this).text()), subjectArray) != -1) {
        $(this).addClass('highlight');
    }
});​

看演示

于 2012-06-26T21:53:41.537 回答
0

在以下行中的逗号后添加一个空格...

subjectArray = subject_passed.split(', ');
于 2012-06-26T21:51:27.180 回答