函数上的jQuery(单击)只影响一个类

时间:2014-08-08 11:11:08

标签: javascript jquery

单击蓝色按钮时会影响两个按钮

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

我的设置看起来像这样

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

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

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

我想只影响我点击的按钮之一

谢谢

2 个答案:

答案 0 :(得分:2)

使用.siblings()获取兄弟姐妹。试试这个:

$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

答案 1 :(得分:2)

您需要定位与单击按钮相关的左/右按钮。因此,您需要将点击的按钮传递到buttonReveal()buttonHide()

所以

(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, $));

演示:Fiddle