简体   繁体   English

jQuery addClass()/ removeClass()无法正常工作

[英]jQuery addClass() / removeClass() not working

<ul>
    <li class="selected"></li>
    <li></li>
    <li></li>
</ul>

That is my html. 那是我的html。 And the selectors I am using right now are: 我现在使用的选择器是:

    $("ul li:eq(0)").removeClass('selected');
    $("ul li:eq(1)").addClass('selected');

Problem is that I can not add or remove the 'selected' class from these elements. 问题是我无法从这些元素中添加或删除“选定”类。 The html and jquery are both pretty straight-forward and as many examples as I could find did everything the same way, including official jQuery docs. html和jquery都非常简单,我可以找到的所有示例都以相同的方式完成了所有操作,包括官方jQuery文档。 (The script is loaded before the body tag, if it matters) (如果需要的话,脚本会在body标签之前加载)

Why can't I remove and add the classes like this? 为什么不能删除和添加这样的类?

The entire html page here 整个html页面在这里

probably because you forgot to add $(document).ready() ,also make sure you added the jquery.min.js file 可能是因为您忘记添加$(document).ready() ,还请确保已添加jquery.min.js文件

$(document).ready( function () {
    $("ul li:eq(0)").removeClass('selected');
    $("ul li:eq(1)").addClass('selected');
});

The code looks correct, the problem must be elsewhere. 该代码看起来正确,问题必须出在其他地方。 How to debug this: 如何进行调试:

  1. Look at how many elements the selector matches: 查看选择器匹配多少个元素:

     console.log($("ul li:eq(1)").length); 

    If you see 0, then the selector didn't match anything. 如果看到0,则选择器不匹配任何内容。

  2. Which element did match? 匹配哪个元素?

     console.log($("ul li:eq(1)")[0]); 

    Most browsers allow to examine the element in the console. 大多数浏览器都允许检查控制台中的元素。

A typical problem is that your code is executed before the elements exist. 一个典型的问题是您的代码在元素存在之前就已执行。 In the simple case, you just need to run your code after the DOM is ready: 在简单的情况下,您只需要在DOM准备好后运行代码:

$(function () {
    ...DOM is now ready...
});

But sometimes, other scripts will create elements. 但是有时,其他脚本会创建元素。 If that's the case for you, you'll need to tell us which frameworks and scripts you use to build / manipulate the DOM. 如果您是这种情况,则需要告诉我们您用于构建/操作DOM的框架和脚本。

Related: 有关:

$("ul li:eq(0)").removeClass('selected');
$("ul li:eq(1)").addClass('selected');

works for me ( http://jsfiddle.net/orlando/rhtqA/ ) 为我工作( http://jsfiddle.net/orlando/rhtqA/

but yeah you need to wait till DOM is ready to do stuff with jquery 但是,是的,您需要等到DOM准备使用jquery进行操作时

$(function () {
    $("ul li:eq(0)").removeClass('selected');
    $("ul li:eq(1)").addClass('selected');
});

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

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