单击更改链接类

时间:2017-06-26 19:25:45

标签: javascript jquery html ajax

我对JS有点新,特别是AJAX。 我想根据我点击的链接更改某个链接的类,以供参考,如下所示:

HTML:

<ul id="top" class="example" style="visibility: visible;">

<li><a style="custom style here" href="#" title="Blonde">Blonde</a></li>

<li><a style="custom style here" href="#" title="Blonde">Blonde</a></li>

<li><a style="custom style here" href="#" title="Brown">Brown</a></li>

<li><a style="custom style here" href="#" title="Black">Black</a></li>

</ul>

(请注意,主题标签只是Ajax调用的占位符)

我目前正在使用jQuery做什么:

jQuery('#top').bind('click',function test(event) { //jQuery because WordPress
    var button = jQuery( event.target.title );
    return button;
});

问题是,无论我如何尝试&#34;获得&#34; button的值似乎永远不会起作用,我尝试输出警报,什么都没有。还尝试将其写入javascript控制台,也没有。

但这只是其余代码中的一个小小问题。 我的最终目标是将所有这些a链接绑定到click事件,然后在点击任何链接时,它会提取title具有的值(棕色,黑色等)链接然后将一个类添加到同一个链接(最终被点击的链接)。

由于超越我的原因,理论上应该检索title值的代码与根据所点击的链接添加CSS类的代码的功能不同,所以总结一下,将变量从一个函数传递到另一个函数是最好的方法吗?

我尝试了这个Passing variables in jquery以及这个Jquery passing a parameter between functions,但由于某些原因它似乎无法工作,可能是因为我以前的错误?

由于

1 个答案:

答案 0 :(得分:0)

希望我理解正确,请尝试以下解决方案并根据需要进行调整。

$("#top a").click(function() {

  $("#top a").removeClass(); // Removes existing classes

  var linkTitle = $(this).attr("title");

  if (linkTitle == "Brown") {

    $(this).addClass("brown"); // You can add the class to something else

  } else if (linkTitle == "Blonde") {

    $(this).addClass("gold");

  } else if (linkTitle == "Black") {

    $(this).addClass("black");

  }

});
.brown {
  color: green;
  font-weight: bold;
}

.gold {
  color: gold;
  font-weight: bold;
}

.black {
  color: black;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="top" class="example" style="visibility: visible;">

  <li><a style="custom style here" href="#" title="Blonde">Blonde</a></li>

  <li><a style="custom style here" href="#" title="Blonde">Blonde</a></li>

  <li><a style="custom style here" href="#" title="Brown">Brown</a></li>

  <li><a style="custom style here" href="#" title="Black">Black</a></li>

</ul>

相关问题