2010-06-22 12 views
5

Chciałbym wiedzieć, który element został kliknięty, aby zmienić jego klasę CSS. Oto kod:Uzyskaj kliknięty element w ButtonSet

<script type="text/javascript"> 
     $(function() { 
     $("#radio").buttonset(); 
     }); 
</script> 

<div id="radio"> 
    <input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label> 
    <input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label> 
    <input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label> 
</div> 

Odpowiedz

0
$("#radio :radio").click(function(){ 
    //alert($(this).attr("id")); 
}); 
0
$('#radio').bind('click', function(event){ 
     $('#radio').removeClass('selected'); 
     $(this).addClass('selected'); 
}); 
2

Można zrobić tak:

$("#radio :radio").click(function(){ 
    alert($(this).attr("id")); // this refers to current clicked radio button 
    $(this).removeClass('class_name').addClass('class_name'); 
}); 
13

zdarzenia jQuery zwraca this jako przedmiot, który opalane zdarzenie. Musisz więc po prostu sprawdzić: this.

Mając to zbiór elementów

<div id="radio"> 
    <input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label> 
    <input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label> 
    <input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label> 
</div> 

Wybierz wszystkie elementy radiowe:

$("#radio :radio") 

następnie powiązać zdarzenie:

.click(function(e) { }); 

pobrać elementu z this:

$("#radio :radio").click(function(e) { 
    var rawElement = this; 
    var $element = $(this); 

    /* Do stuff with the element that fired the event */ 
}); 

Example on jsFiddle.

find here functions można manipulować klasę elementu.

+0

Co czyni tę część myśli: 'var $ element = $ (this); '? Czym różni się '$ element'? Co byś z tym zrobił? –

+0

@jeffamaphone 'this' jest węzłem DOM. '$ (this)' jest obiektem jQuery, który zawiera węzeł DOM – BrunoLM

5

Można również pobrać wybraną opcję z buttonset używając:

$j("#radioset :radio:checked") 

wtedy robić, co chcesz z elementem ...

+0

Jestem ciekawy, co oznacza "$ j" czy jest to literówka? –

0
$('#radio').buttonset().find(':radio').click(function(e) { 
    var $radio = $(this); 
    $radio.addClass('active'); 
}); 
Powiązane problemy