Mark
Mark

Reputation: 33551

jquery: $(this) confusion

I have 3 buttons. I'm trying to get it so that when one is clicked it gets a class of 'this-button' and the class is removed from others.

  <button id="button1">Button1</button>
  <button id="button2">Button2</button>
  <button id="button3">Button3</button>

So here's my simple event function:

$('button').live("click", function (){
    $(this).addClass("this-button").siblings().removeClass("this-button");
});

This does not work as expected.

Here's to try: check the classes in firebug. http://jsbin.com/orifo/edit

I'm really very confused. I think it's clear that $(this) refers to all the buttons, rather than just the one latest clicked. Why is this? Shouldn't it be the one latest clicked?

Can someone explain why this doesn't work.

Thanks.

Upvotes: 1

Views: 106

Answers (2)

bobince
bobince

Reputation: 536329

Why is this? Shouldn't it be the one latest clicked?

Yes, it is the one clicked. Works fine for me. Here's the exact snippet I tested.

<style>
    .this-button { border: solid red 1px; }
</style>
<body>
<div>
    <button id="button1">Button1</button>
    <button id="button2">Button2</button>
    <button id="button3">Button3</button>
</div>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
    $('button').live('click', function() {
        $(this).addClass('this-button').siblings().removeClass('this-button');
    });
</script>
</body>

Upvotes: 1

David Andres
David Andres

Reputation: 31781

This works on my end. I'm using IE 7 and jQuery 1.32.

Upvotes: 0

Related Questions