我想用jQuery更改链接的颜色。当我尝试引用该对象时出现错误。
我的HTML:
<a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>
我的JS:
function loclink(a){
a.css("color", "red"); // Didn't work
jQuery('a').find('.nav-link').css("color", "red"); // Didn't work
$(a).find('.nav-link').css("color", "red"); // Didn't work
console.log(a):
<a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>
答案 0 :(得分:2)
function loclink(a){
$(a).css("color", "red"); // this should work
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>
更好的方法(而不是使用内联事件)是使用Jquery.on将事件处理程序附加到您的链接
$("a.nav-link").on("mouseover",function (){
$(this).css("color", "red"); // this should work
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>