仅当链接文本在数组

时间:2017-05-05 13:35:54

标签: jquery arrays

我有一个数组:

var List2 = ['Maine', 'Maryland', 'Massachusetts', 'New Jersey', 'Oklahoma'];

我有php生成的表行,其中包含链接,每个链接都有.one。

<a class="one" href="http://www.maine.gov/aPage.shtml">Maine</a>
<a class="one" href="https://www.colorado.gov/aPage.aspx">Colorado</a>

单击链接后,如果链接文本中的状态位于数组中(例如,缅因州),则目标是打开div,但如果链接文本中的状态不在数组中,则打开链接(例如,科罗拉多州)

为此,我想将一个类.openDiv添加到那些链接文本出现在数组中的人。然后.openDiv将用于打开div。

我正在迭代(我认为)使用each()查找数组中包含文本的所有链接并应用openDiv。

当我手动测试它们时,两个链接都正常工作,但是我的addClass代码将.openDiv应用于列表中的每个链接,而我不知道如何将其限制为只有数组中的链接。我的.js脚本位于页面底部。

这是代码

$(document).ready(function() 
{var List2 = ['Idaho', 'District of Columbia', 'Maine', 'Maryland', 'New Jersey', 'Oklahoma'];

$("a[href]").each(function() {
if(jQuery.inArray($("a[href]").html(), List2) !== -1) {
$("a[href]").addClass('openDiv');
}
});
$(".openDiv").click(function(e) {
e.preventDefault();
$("#notInList1").slideToggle(200);
});
 });

我已经尝试了

$("a[href]").text()

和各种形式的这个,但没有去。我已经阅读了3或4个其他问题,但没有一个是相同的。 有谁知道我应该如何使用$ this来修复它,还是我的每个()函数搞砸了?

1 个答案:

答案 0 :(得分:2)

问题是因为您在添加课程时选择了所有a[href]元素。而是使用this处理程序中的each()关键字将类添加到当前元素:

$(document).ready(function() {
  var List2 = ['Idaho', 'District of Columbia', 'Maine', 'Maryland', 'New Jersey', 'Oklahoma'];

  $("a[href]").each(function() {
    if (List2.indexOf($(this).text()) != -1) {
      $(this).addClass('openDiv'); // note 'this' here
    }
  });
});
.openDiv { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="one" href="http://www.maine.gov/aPage.shtml">Maine</a>
<a class="one" href="https://www.colorado.gov/aPage.aspx">Colorado</a>