program story

jquery를 사용하여 라디오에서 이벤트를 클릭하거나 변경하십시오.

inputbox 2020. 9. 18. 08:08
반응형

jquery를 사용하여 라디오에서 이벤트를 클릭하거나 변경하십시오.


내 페이지에 라디오가 있고 확인 된 라디오가 변경되면 코드가 IE에서 작동하지 않습니다.

$('input:radio').change(...);

인터넷 검색 후 사람들은 대신 클릭을 사용하도록 제안합니다 . 그러나 작동하지 않습니다.

다음은 예제 코드입니다.

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
        <script type="text/javascript">
            $('document').ready(
                function(){
                    $('input:radio').click(
                        function(){
                            alert('changed');   
                        }
                    );  
                }
            );

        </script>
    </head>
    <body>
        <input type="radio" name="testGroup" id="test1" />test1<br/>
        <input type="radio" name="testGroup" id="test2" />test2<br/>
        <input type="radio" name="testGroup" id="test3" />test3</br>
    </body>
</html>

IE에서도 작동하지 않습니다.

그래서 무슨 일이 일어나고 있는지 알고 싶어요?

또한 확인 된 라디오를 클릭하면 변경 이벤트가 다시 트리거 될까 두렵습니까?

최신 정보:

댓글을 달 수 없으니 여기에 답장하겠습니다.

IE8을 사용하고 Furqan이 제공하는 링크도 IE8에서 작동하지 않습니다. 이유를 모르겠습니다 ...


이 코드는 나를 위해 일했습니다.

$(function(){

    $('input:radio').change(function(){
        alert('changed');   
    });          

});

http://jsfiddle.net/3q29L/


아래와 같이 이름 속성을 지정할 수 있습니다.

$( 'input[name="testGroup"]:radio' ).change(

저에게도 작동합니다. 여기에 더 나은 솔루션이 있습니다.

바이올린 데모

<form id="myForm">
  <input type="radio" name="radioName" value="1" />one<br />
  <input type="radio" name="radioName" value="2" />two 
</form>

<script>
$('#myForm input[type=radio]').change(function() {       
    alert(this.value);
});
</script>

You must make sure that you initialized jquery above all other imports and javascript functions. Because $ is a jquery function. Even

$(function(){
 <code>
}); 

will not check jquery initialised or not. It will ensure that <code> will run only after all the javascripts are initialized.


Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

$( 'input[name="testGroup"]:radio' ).on('change', function(e) {
     console.log(e.type);
     return false;
});

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.

참고URL : https://stackoverflow.com/questions/5165862/click-or-change-event-on-radio-using-jquery

반응형