Javascript 我想改变一个特定元素的类,你能告诉我为什么我的代码不工作吗?

Javascript 我想改变一个特定元素的类,你能告诉我为什么我的代码不工作吗?,javascript,jquery,html,Javascript,Jquery,Html,我想更改特定元素的类,我找到了几种方法,但都不起作用,您能告诉我代码不起作用的原因吗> <script type="text/javascript"> $('.header a[href="register_friend.php"]').parent().setAttribute("class", "active"); </script> <header class="header" > <nav><ul&g

我想更改特定
  • 元素的类,我找到了几种方法,但都不起作用,您能告诉我代码不起作用的原因吗>

    <script type="text/javascript">
            $('.header a[href="register_friend.php"]').parent().setAttribute("class", "active");
        </script>
    
    <header class="header" >
        <nav><ul>
                <li class="active"><a href="index.html">Home</a></li>
                <li><a href="register_friend.php">Register a friend</a></li>
                <li><a href="">Register Yourself</a></li>
                <li><a href="">Contact</a></li>
                <li><a href="index.html">Rate</a></li>
            </ul>
        </nav>
    </header>
    
    
    $('.header a[href=“register_friend.php”]').parent().setAttribute(“类”,“活动”);
    
    我想补充一点,我正在使用一个外部标题,如果这带来任何变化的话

    <body >
    <div id="header"></div>
    
    </body>
    
    
    
    
    document.addEventListener(“DOMContentLoaded”,function()){
    $('.header a[href=“register_friend.php”]').parent().addClass(“active”);
    });
    
    在API文档中查找addClass

    对addEventListner的警告: 对于IE:

    尝试用以下方式包装脚本:

    $(document).ready(function(){
         // Note:jquery use 'attr', instead of 'setAttribute' to set attribute.
        $('.header a[href="register_friend"]').parent().attr("class", "active");
    })
    

    您需要获取DOM节点本身,以便可以使用本机的
    setAttribute
    ,或者在jQuery对象上使用jQuery
    .attr()
    。这两种方法都可以工作(假设在脚本运行时存在DOM节点——如果需要,请执行通常的document.ready舞蹈)

    //使用DOM节点:
    $('.header a[href=“register\u friend.php”]').parent()[0].setAttribute(“类”,“活动”);
    //或者使用jQuery对象:
    $('.header a[href=“register_friend.php”]').parent().attr(“类”,“活动”)
    
    .active{
    边框:1px实心#F00
    }
    
    

    首先,您应该使用
    addClass
    ,而不是设置属性

    除此之外,如果希望在页面加载时发生这种情况,则应将jQuery函数包装到
    $(document).ready(function(){…})

    $(文档).ready(函数(){
    $('.header a[href=“register_friend.php”]').parent().addClass(“active”);
    });
    
    .active{
    边框:1px纯红;
    }
    
    

    试着在标题下方放置。setAttribute()是一个普通的JS方法,您尝试在jQuery对象上使用它。添加@selten98所说的内容,我认为解释原因很重要。您的javascript在类
    加载之前执行,因此,它无法对该类执行操作,因为该类尚不存在。此外,您在控制台中遇到了哪些错误?@j08691不幸的是,控制台中没有错误,这是主要问题:Pdidn不工作,还尝试了addClass()函数,是否有其他方法?:(再次发布您正在运行的代码。是的,代码笔链接正在工作。
    $(document).ready(function(){
         // Note:jquery use 'attr', instead of 'setAttribute' to set attribute.
        $('.header a[href="register_friend"]').parent().attr("class", "active");
    })