javascript - jQuery/Javascript - 从数组中的无序列表中查找字符串

标签 javascript jquery arrays

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

相关文章:

javascript - Angularjs未定义错误范围变量

javascript - 尝试创建一个Java脚本函数,当按下按钮时会出现图像

c - 如果a是数组(比如int a[4];),那么&a是什么?

javascript - 事件处理程序 : Enable Button 2 when clicked on Button 1

javascript - 在 MVC 5 Razor View 中调用 JavaScript 函数

java - 在数组的构造函数下,我有一个 toString 方法来打印内容。但它告诉我它没有解析为变量

javascript - 从下拉菜单中的数组中取回特定项目

javascript - 将 2D 方向应用于粒子 - three.js

javascript - 如何访问这个 Javascript mysql 错误对象 (Nodejs)?

php - 使用 CSRF token 的 Laravel API 请求