简体   繁体   English

jQuery on function(单击)仅影响一个类

[英]jQuery on function (click) only affect one class

When the blue button is clicked it affects both buttons 单击蓝色按钮时,它会同时影响两个按钮

http://jsfiddle.net/umbriel/Lwvukzhy/1/ http://jsfiddle.net/umbriel/Lwvukzhy/1/

My setup looks like this 我的设置看起来像这样

var
    $window = $(window),
    $body = $('body'),
    $buttonRight = $('.button .right')
 ;

$buttonRight.on('click', function( ) {
    buttonReveal(  $( this ) );
});

function buttonReveal() {
    $buttonLeft.css({'width':'25%'});
    $buttonRight.css({'width':'75%'});
}

I want to to only affect one of buttons I clicked 我只想影响单击的按钮之一

Thank you 谢谢

Use .siblings() to get siblings. 使用.siblings()获取同级。 Try this: 尝试这个:

$buttonRight.on('click', function( ) {
    buttonReveal($(this)); //$(this) refers to current clicked element (button)
});
$buttonLeft.on('click', function() {
    buttonHide($(this));   //$(this) refers to current clicked element (button)
});


function buttonReveal(element) {
    element.siblings($buttonLeft).css({'width':'25%'}); //to apply css to siblings use .siblings()
    element.css({'width':'75%'});
}

function buttonHide(element) {
    element.css({'width':'0%'});
    element.siblings($buttonRight).css({'width':'100%'});
}

DEMO DEMO

You need to target the left/right buttons which is related to the clicked button. 您需要定位与单击按钮相关的左/右按钮。 So you need to pass the clicked button to buttonReveal() and buttonHide() . 因此,您需要将单击的按钮传递给buttonReveal()buttonHide()

So 所以

(function (window, $) {

    var
    $window = $(window),
        globalTimeout = null,
        $body = $('body'),
        $buttonRight = $('.button .right'),
        $buttonLeft = $('.button .left');


    $buttonRight.on('click', function () {
        buttonReveal(this);
    });
    $buttonLeft.on('click', function () {
        buttonHide(this);
    });


    function buttonReveal(button) {
        var $btn = $(button).css({
            'width': '75%'
        });
        $btn.prev('.left').css({
            'width': '25%'
        });
    }

    function buttonHide(button) {
        var $btn = $(button).css({
            'width': '0%'
        });
        $btn.next('.right').css({
            'width': '100%'
        });
    }

}(window, $));

Demo: Fiddle 演示: 小提琴

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

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