检查元素是否具有活动的类,如果是,将类添加到不同的元素 [英] Check if element has the class active, if so, add class to a different element

查看:149
本文介绍了检查元素是否具有活动的类,如果是,将类添加到不同的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为客户端构建一个网站,但只为主页我需要得到一个类的主div为css目的。为此,我试图在home菜单项中寻找一个活动类,如果它有活动类,那么为主网页的div添加一个不同的类。

Building a website for a client but only for the mainpage I need to get a class on the main div for css purposes. For this I am trying to look for an active class on menu item for home, and if it has the active class, then add a different class to the main webpage's div.

到目前为止,我无法得到更多的进一步,这样:

so far i cant get much further then this:

<script>
$(document).ready(function() { 
if $('li.level1.item101').hasClass('active');
$('#main').addClass('woodwork');}
});
</script>

所涉及的html(li项目)看起来像这样当活动与下面的div在页面本身

the html involved for this (the li item) looks like this when active with the div somewhere down below in the page itself

<li class="level1 item101 active current"> </li>
<li class="level1 item102"> </li>
<div id="main"> </div>

我当前的代码似乎不能抓住活动的li或div,任何帮助会非常感谢。

my current code doesn't seem to be able to grab either the active li or the div, any help would be greatly appreciated

推荐答案

首先,你的代码有一些错误,html应该是:

First of all, you have some errors with your code, the html should be:

<li class="level1 item101 active current"> active</li>
<li class="level1 item102"> second</li>
<div id="main"> main </div>

和javascript:

and the javascript:

$(document).ready(function(){
  if ( $('li.level1.item101').hasClass('active') ) {
    $('#main').addClass('woodwork');
  }
});

这是一个正常的小提琴

这篇关于检查元素是否具有活动的类,如果是,将类添加到不同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆