javascript jQuery 添加类不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14709461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:22:23  来源:igfitidea点击:

jQuery Add Class doesn't work

javascriptjquery

提问by DerFuchs10

I want to add a class to an object when I click on an div with the class "arrow right" or "arrow left". On http://jsfiddle.net/does it work perfect. But on my Site it doesn't work :(

当我单击带有“向右箭头”或“向左箭头”类的 div 时,我想向对象添加一个类。在http://jsfiddle.net/上它是否完美运行。但在我的网站上它不起作用:(

Can anyone help me?

谁能帮我?

jQuery:

jQuery:

var currentPage = 0;
var lastPage = ($(".post-preview > div").length)-1;
currentPage = $('.post-preview > div.show').attr('id');

$('.news > .right').stop().click(function() {
    if (currentPage == lastPage) {
            $('.post-preview > div#' + lastPage).hide();
            $('.post-preview > div#' + lastPage).removeClass('show');

        $('.post-preview > div#0').fadeIn(300);
        $('.post-preview > div#0').addClass('show');
        currentPage = 0;
    } else {
        $('.post-preview > div#'+currentPage).hide();
        $('.post-preview > div#'+currentPage).removeClass('show');
        currentPage++;
        var nextPage = currentPage;
        currentPage--;
        $('.post-preview > div#'+nextPage).fadeIn(300);
        $('.post-preview > div#'+nextPage).addClass('show');
        currentPage = nextPage;
    }
 });

 $('.news > .left').stop().click(function() {
     if (currentPage == 0) {
        $('.post-preview > div#0').hide();
        $('.post-preview > div#0').removeClass('show');

        $('.post-preview > div#' + lastPage).fadeIn(300);
        $('.post-preview > div#' + lastPage).addClass('show');
        currentPage = lastPage;
    } else {
        $('.post-preview > div#'+currentPage).hide();
        $('.rpost-preview > div#'+currentPage).removeClass('show');
        currentPage--;
        var nextPage = currentPage;
        currentPage++;
        $('.post-preview > div#'+nextPage).fadeIn(300);
        $('.post-preview > div#'+nextPage).addClass('show');
        currentPage = nextPage;
    }
});

CSS for show class:

显示类的 CSS:

.news > .post-preview > div.show    { display: inline-block !important; }

My HTML Code:

我的 HTML 代码:

<div class="news">
<div class="arrow left"></div>
    <div class="post-preview">
        <div id="0" class='show'></div>
        <div id="1"></div>
        <div id="2"></div>

    </div>
<div class="arrow right"></div>
</div>

回答by Yanick Rochon

You are trying to access an element that probably does not exist at the time of the execution. This is why it doesn't work.

您正在尝试访问在执行时可能不存在的元素。这就是它不起作用的原因。

You need to wrap your code inside a $(function() { /* put code here */ } );block.

您需要将代码包装在一个$(function() { /* put code here */ } );块中。

The reason why it works on jsfiddleis because the site does it for you as convenience.

它在jsfiddle上工作的原因是因为该站点为您提供方便。

** Edit**

**编辑**

In JavaScript, it is a good (if not best) practice to enclose your code inside it's own context. Take a look at the jQuery, jQuery UI and many JavaScript widgets and libraries. For example :

在 JavaScript 中,将代码包含在它自己的上下文中是一个很好的(如果不是最好的)实践。看看 jQuery、jQuery UI 和许多 JavaScript 小部件和库。例如 :

(function($) {    // receive $ as parameter; a jQuery instance

    /* place code here

})(jQuery);   // invoke the function above with this instance of jQuery

The reason for this is

这样做的原因是

  1. If you need to use a different version of jQuery, or are using a library that overrides the $variable, this function above will notget affected by the changes
  2. Every variables declared (ie. var x = "foo";) will notbe available outside the function, so you are certain that you are not polluting the window (global) namespace and have the right value when you need it. (Expose a global object if you need access to something outside the function (Ex: window.someVar = localVar;)
  1. 如果您需要使用不同版本的 jQuery,或者正在使用覆盖$变量的库,则上述函数不会受到更改的影响
  2. 声明的每个变量(即var x = "foo";)在函数外都将不可用,因此您可以确定不会污染窗口(全局)命名空间,并且在需要时具有正确的值。如果你需要的功能(防爆外部访问的东西(揭露一个全局对象:window.someVar = localVar;

However, the above function will get executed as it is loaded by the browser, and might get executed beforeany DOM element is inserted into the DOM tree. This can be a problem for scripts setting up event listeners and such. Thus, if you need the function to be executed onlywhen the DOM element is completely loaded and ready to be used, enclose your code inside a jQuery onload callback :

但是,上述函数将在浏览器加载时执行,并且可能任何 DOM 元素插入 DOM 树之前执行。对于设置事件侦听器等的脚本来说,这可能是一个问题。因此,如果您需要在 DOM 元素完全加载并准备好使用时才执行该函数,请将您的代码包含在 jQuery onload 回调中:

jQuery(function() {

    /* place code here */

});

or even

甚至

(function($) {
    // executed right now

    $(function() {
        // executed only when the DOM is ready

        /* place code here */

    });

})(jQuery);

** Update**

**更新**

After reading your code a little further, I can only see (as commented) some odd things.

在进一步阅读您的代码后,我只能看到(如评论)一些奇怪的东西。

  1. Your IDs are numeric. Fromthe HTML specification,

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    So you should a an id prefix... or base your selection on element indexes

  2. You can chain your queries instead of reparsing them all the time.

  1. 您的 ID 是数字。HTML规范

    ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号 (":") 和句点 (".")。

    所以你应该一个 id 前缀......或者根据元素索引进行选择

  2. 您可以链接您的查询,而不是一直重新解析它们。

For example

例如

jQuery(function() {

var firstPage = $(".post-preview > div:first").index(); // index of the first page
var lastPage = $(".post-preview > div:last").index(); // index of the last page
var currentPage = $('.post-preview > div.show').index() || firstPage;  // default to 0

$('.news > .right').stop().click(function() {
    if (currentPage == lastPage) {
        currentPage = $('.post-preview > div:eq(' + lastPage + ')')
           .hide()
           .removeClass('show')
           .siblings('div:first')  // first DIV
           .fadeIn(300)
           .addClass('show')
           .index();  // should be 0... but we never know
    } else {
        // note : will receive the next element index
        currentPage = $('.post-preview > div:eq(' + currentPage + ')')
           .hide()
           .removeClass('show')
           .next('div')             // get next DIV element
           .fadeIn(300)
           .addClass('show')
           .index();
    }
 });

 $('.news > .left').stop().click(function() {
     if (currentPage == firstPage) {
        currentPage = $('.post-preview > div:eq(' + currentPage + ')')
           .hide()
           .removeClass('show')
           .siblings('div:last')  // last DIV
           .fadeIn(300)
           .addClass('show')
           .index();
    } else {
        currentPage = $('.post-preview > div:eq(' + currentPage + ')')
           .hide()
           .removeClass('show')
           .prev('div')
           .fadeIn(300)
           .addClass('show')
           .index();
    }
});

});

And your HTML (no need for IDs anymore)

还有你的 HTML(不再需要 ID)

<div class="news">
<div class="arrow left"></div>
    <div class="post-preview">
        <div class='show'>Preview 1</div>
        <div>Preview 2</div>
        <div>Preview 3</div>
    </div>
</div>
</div>