开发者

"#button_1" isn't affected by .click() or .hover()

Probably a rookie mistake, but my #button_1 ID isn't affected by the click() or hover() jQuery 开发者_Python百科effects.

If someone could take a quick look at my JSFiddle, it would be greatly appreciated.

It's probably pretty obvious, but I want #button_1 to act as every other button. :)

Again, I suspect it's a pretty stupid mistake, something that I've overlooked.


Don't repeat so much code , try this and its working

Try line by line , its throwing error in somewhere in the code and breaking the bind events. you have some error in hover or so , remove everything and have bind events, they are work.

You know this right ,when line 1 breaks in documentready , all bindings below may not get binded.

$(document).ready( function () {

   $('#button_1,#button_2').click(function() {
  alert('Handler for .click() called.');

   });

});


Might I suggest condensing that code a little, to something closer to:

$('a div[class^="button"]').click(
    function(e){
        e.stopPropagation(); // prevent the click bubbling to the parent 'a' element
        $('.button_active')
            .removeClass('button_active')
            .addClass('button_normal');
        $(this).addClass('button_active').removeClass('button_normal');
    });

JS Fiddle demo.


Edited in response to question from the OP:

Just to add, [the Fiddle updated by the OP to include the above code] actually sets "button_hover" as the class instead of "button_active", any idea why that would be?

Yep; that's in response to the specificity of the CSS selectors, I add and remove classes as needed in response events (rather than repeatedly checking for whether or not button_hover is set). As the element ends up with class="button_normal button_hover", and the order of the css (I think) places greater emphasis on the later-declared class, button_hover is maintained. It's late, and I'm a bit tired, but that's sort of (in a nutshell) what's happening.

The following demo incorporates everything (I think) that you need, and, coupled with revised CSS selectors, should do as you want:

$('a div[class^="button"]').hover(
    function(){
        $(this).addClass('button_hover').click(
            function(e){
                e.preventDefault();
                $('.button_active')
                    .addClass('button_normal')
                    .removeClass('button_active');
                $(this).addClass('button_active').removeClass('button_hover');
            });
    },
    function(){
        $(this).removeClass('button_hover');
    });

CSS:

.button_active,
.button_normal.button_active { background: #000; }
.button_normal.button_hover { background: #ff0; }
.button_normal { background: #d89; }

JS Fiddle demo.


References:

  • attribute-begins-with (^=) selector.
  • e.stopPropagation().
  • removeClass().
  • addClass().
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜