简体   繁体   English

如何在body标签/ div上添加和更改类

[英]How to add and change a class on the body tag/div

I want to add a class on the body tag/div and on the anchor tag when I click an anchor tag. 我想在单击锚标记时在body标记/ div和锚标记上添加一个类。

Here is my jsFiddle File. 这是我的jsFiddle文件。

<div id="body">
 <!-- background image here -->

</div>

<ul>
    <li><a href="#">First Option</a></li>
    <li><a href="#">Second Option</a></li>
    <li><a href="#">Third Option</a></li>
</ul>​

http://jsfiddle.net/4nFUd/5/ http://jsfiddle.net/4nFUd/5/

Add an event listener to the click and modify as needed... 为点击添加一个事件监听器并根据需要进行修改......

<script>
$('ul').on('click','a',function(){
    $('#body').css('background',$(this).attr('rel'));
    $(this).addClass($(this).attr('rel'));
});
</script>
<div id="body">
 <!-- background image here -->

</div>

<ul>
    <li><a href="#" rel="blue">First Option</a></li>
    <li><a href="#" rel="green">Second Option</a></li>
    <li><a href="#" rel="yellow">Third Option</a></li>
</ul>

That should do the trick. 这应该够了吧。

$("li a").click(function(){
  $(this).addClass("class1");
  $("#body").addClass("class2");
});

here it is, ad class to body and anchor itself http://jsfiddle.net/testtracker/4nFUd/2/ 在这里,广告类到身体并锚定自己http://jsfiddle.net/testtracker/4nFUd/2/

$('ul li a').click(function(){
$('#body').addClass('classname-tobody');
$(this).addClass('classname-toanchor');
});​

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

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