2010-06-22 34 views
5

Tôi muốn biết phần tử nào được nhấp để tôi có thể thay đổi lớp CSS của nó. Đây là mã:Lấy phần tử được nhấp vào trong 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> 

Trả lời

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

Bạn có thể làm như sau:

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

jQuery sự kiện trả this như đối tượng mà bắn sự kiện này. Vì vậy, bạn chỉ cần kiểm tra this.

Có này tập hợp các yếu tố

<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> 

Chọn tất cả các nguyên tố phóng xạ:

$("#radio :radio") 

Sau đó ràng buộc một sự kiện:

.click(function(e) { }); 

Lấy phần tử với this:

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

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

Example on jsFiddle.

Bạn có thể find here functions để thao tác lớp của phần tử.

+0

gì phần này có nghĩa là: 'var $ element = $ (this); '? '$ Element' khác nhau như thế nào? Bạn sẽ làm gì với điều đó? –

+0

@jeffamaphone 'this' là nút DOM. '$ (this)' là đối tượng jQuery chứa nút DOM – BrunoLM

5

Bạn cũng có thể lấy lại nút radio được chọn ra khỏi buttonset sử dụng:

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

sau đó làm bất cứ điều gì bạn muốn với phần tử ...

+0

Tôi tò mò về những gì "$ j" có nghĩa là hoặc là một lỗi đánh máy? –

0
$('#radio').buttonset().find(':radio').click(function(e) { 
    var $radio = $(this); 
    $radio.addClass('active'); 
}); 
Các vấn đề liên quan