简体   繁体   中英

click event on input button

I try to bind a function to the click event on input button, but it doesn't seems to work and method is not called:

<div id='back'>


     <input type="button"/>

     </div>

jQuery:

 $('#back').click(clickOnBackbutton);

              function clickOnBackbutton(){

                console.log('back to menu'); //function not called 

              }

I do not prefer to use onClick event, instead i prefer to use that approach. Thanx in advance.

You should put your code within document ready handler. also note that you are selecting the div tag instead of the input element.

$(document).ready(function(){
   $('#back input[type=button]').click(clickOnBackbutton);
   // $('#back input[type=button]').click(function(){
   //    or do something here
   // });
})

Button:

<div id='back'>
    <input type="button" id='back-button'/>
</div>

jQuery:

$(document).ready(function(){
    $('#back-button').click(function(){
       console.log('Back to Menu');
    });
})

You bound to the div not the button.

give the button a name or select it as a child then bind the click event.

<div id='back'>
    <input id='backbutton' type="button"/>
</div>

JQuery

$('#backbutton').click(clickOnBackbutton);

function clickOnBackbutton(){
    console.log('back to menu'); //function not called 
}

This should work:

function clickOnBackButton(){
  console.log("back to menu");
}

$('#back').click(function(){
  clickOnBackButton();
});

You could do this

$('#back').click(function(){
    clickOnBackButton();
});

I don't think there's such a thing as an input type="button". Maybe type="submit" ?

Also you can use:

$('#back').on('click', function(){
  // some action
});

JQuery 1.7+ you should attach the event using on.

function clickOnBackbutton(){
    console.log('back to menu'); //function not called 
}
$(document).on("click", "#back", clickOnBackbutton);

Running example

If you want div#back to capture clicked button event, then with the recent jquery you have to do this:

$('#back').on("click", "input[type=button]", clickOnBackbutton);

Note that you have to put script tag in the end of body, or wrap your code in $(document).ready event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM