简体   繁体   English

jQuery无法识别元素上的类更改

[英]jQuery not recognising change of class on element

OK so I made a custom function which I can then call using a div's class. 好的,所以我做了一个自定义函数,然后可以使用div的类进行调用。

I target the class 'back' then this function is applied which enlarges and moves the div. 我将目标定为“后退”类,然后应用此函数来放大和移动div。 Once this animation is complete, I remove the class 'back' and add the class 'front'. 完成此动画后,我将删除“ back”类,并添加“ front”类。

I have another function which is looking for a click on the element with class 'front', however when I click this element, which only has the class 'front' and not 'back' it is still triggering the first function. 我还有另一个函数正在单击具有“ front”类的元素,但是当我单击该元素时,该元素仅具有“ front”类而不是“ back”,它仍在触发第一个函数。

How can this be if it doesn't have that class anymore? 如果不再有该类怎么办?

Here is my code... 这是我的代码...

$(document).ready(function () {
    "use strict";

    (function ($) {
        $.fn.expand = function () {

            var wide = this.css('width').replace(/[^-\d\.]/g, '') * 10;
            var high = this.css('height').replace(/[^-\d\.]/g, '') * 10;
            var marg = -(wide / 2);
            $(this).removeClass('back');
            $(this).animate({
                'width': wide,
                'height': high,
                'margin-left': marg,
                'bottom': '0'
            }, 3000, 'easeInOutCubic', function () {
                $(this).addClass('front');
            });

        };
    })(jQuery);

    $('.back').click(function () {
        $(this).expand();
        $('.wall').animate({
            'bottom': '+=10px'
        }, 3000, 'easeInOutCubic');
    });

    $('.front').click(function () {
        $('.wall').animate({
            'bottom': '-=100px'
        }, 300);
        $('.floor').animate({
            'bottom': '-=100px'
        }, 300);
    });
}); // JavaScript Document

...and the current file here.. http://thetally.efinancialnews.com/tallyassets/chinahurdles/index.html ...和当前文件在这里。.http: //thetally.efinancialnews.com/tallyassets/chinahurdles/index.html

The problem is caused by statically attaching event handlers to elements with classes of .back and .front at load time . 该问题是由于在加载时将事件处理程序静态附加到具有.back和.front类的元素而引起的。 The handers stay attached to those specific elements, even if you change the classes. 即使您更改类,处理程序仍将与那些特定元素保持联系。

As the classes change dynamically, use delegated event handlers attached to a non-changing ancestor element ( document is the best default if nothing else is closer/convenient) . 当类动态变化时,请使用附加到不变的祖先元素的委托事件处理程序(如果没有其他更方便的方法, document是最好的默认值)

$(document).on('click', '.back', function() {
    $(this).expand();
    $('.wall').animate({'bottom':'+=10px'}, 3000, 'easeInOutCubic');
});

$(document).on('click', '.front', function() {
    $('.wall').animate({'bottom':'-=100px'}, 300);
    $('.floor').animate({'bottom':'-=100px'}, 300);
});

Delegated events work by listening for an event to bubble up to the targeted ancestor element (in this case document ), then they apply the jQuery selector to only the elements in the bubble chain , then it applies the function to any matching elements that actually caused the event . 委托事件的工作方式是监听事件,使事件冒泡到目标祖先元素(在本例中为document ), 然后将jQuery选择器应用于冒泡链中的元素然后将函数应用于实际上引起的任何匹配元素事件

Basically they evaluate the selector at event time , not when the event was registered , so work with dynamically changed/added content. 基本上,他们在事件发生时 (而不是在事件注册时)评估选择器,因此可以处理动态更改/添加的内容。

Side note: 边注:

You have nested two DOM ready handlers. 您已经嵌套了两个DOM ready处理程序。 $(function ($) { is just a shortcut for $(document).ready( with a locally scoped $ . Although nesting DOM ready handlers is harmless, it is a waste (as the inner one fires immediately) $(function ($) {只是$(document).ready(具有局部作用域$的快捷方式。尽管嵌套DOM ready处理程序是无害的,但这是一种浪费(因为内部的立即被触发)

Use either just this: 仅使用此一项:

$(document).ready(function () {
    "use strict";
    $.fn.expand = function () {

or 要么

jQuery(function ($) {
    $.fn.expand = function () {
    ...
});

The problem is that browser reads all your handlers and applies its ones page is loaded. 问题在于浏览器会读取您的所有处理程序并应用其页面加载。 So it's wrong to set handler to class. 因此,将处理程序设置为类是错误的。 Class is only specifier to find specific DOM element 类仅是查找特定DOM元素的说明符

I suggest you to use next solution Use on event on any parent element and apply your handler to it 我建议您使用下一个解决方案在任何父元素上使用on事件,并将处理程序应用于该事件

$(document).on('click', '.front', function() {
});

$(document).on('click', '.back', function() {
});

So each time your click has fired on element it propagates to element with handler, and will search to call exactly callback with specific selector (class .back or .front) 因此,每次您的点击在元素上触发时,它都会传播到带有处理程序的元素,并将搜索以特定选择器(类.back或.front)确切地调用回调

You have added a listener to the DOM element. 您已将侦听器添加到DOM元素。 Changing the elements classes won't remove the listeners you have already attached. 更改elements类不会删除您已附加的侦听器。 The closest solution to what you have tried to do with classes would be something like this: 与您尝试对类进行处理的最接近的解决方案是这样的:

$( document ).ready(function() {
    "use strict";

    (function($){
        $.fn.expand = function() {

            var wide = this.css('width').replace(/[^-\d\.]/g, '')*10;
            var high = this.css('height').replace(/[^-\d\.]/g, '')*10;

            var marg = - ( wide / 2 );

            $(this).unbind("click");
            $(this).animate({'width' : wide ,'height': high, 'margin-left': marg, 'bottom':'0' }, 3000, 'easeInOutCubic', function() {
                $(this).click(frontFunction);
            });

        };

        $('.back').click(backFunction);
    })(jQuery);

    var backFunction = function() {
        $(this).expand();
        $('.wall').animate({'bottom':'+=10px'}, 3000, 'easeInOutCubic');
    };

    var frontFunction = function() {
        $('.wall').animate({'bottom':'-=100px'}, 300);
        $('.floor').animate({'bottom':'-=100px'}, 300);
    };


});

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

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