简体   繁体   English

使用类X JavaScript更改所有链接的颜色

[英]Change color of all links with class X JavaScript

Link with example 链接示例

I am using the following function: 我使用以下功能:

<div align="center"><a href="#" onclick="changeColor('A'); return false;">A</a>
<script>
    function changeColor(id)
    {
        document.getElementById(id).style.color = "#FFF"; // forecolor
        document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
    }
</script>

When, for example, I click on A on the page with the example, only the first link is changing colors because the script is changing colors by id. 例如,当我点击带有示例的页面上的A时,只有第一个链接正在改变颜色,因为脚本正在通过id更改颜色。 How can I change all link colors by class? 如何按班级更改所有链接颜色?

What I want is when I click on A, all links with class A should change their color, and when I click B, all links with class B should change their color, etc. 我想要的是当我点击A时,所有与A类的链接都应该改变它们的颜色,当我点击B时,所有与B类的链接都应该改变它们的颜色等。

function changeColor( _class ) {
    var elems = document.getElementsByClassName( _class );
    for (var i=elems.length; i--;) {
        elems[i].style.color = "#FFF";
        elems[i].style.backgroundColor = "#ff0000";
    }
}

FIDDLE 小提琴

Change the function to the above, and pass a class to it instead ? 将函数更改为上面的函数,然后将类传递给它?

jQuery version: jQuery版本:

$('div[align="center"] > a').on('click', function(e) {
    e.preventDefault();
    $('.' + $.trim($(this).text())).css({color: '#fff', backgroundColor: '#ff0000'});
});

with HTML 用HTML

<div align="center"><a href="#">A</a></div>

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM