Ajax调用 - 按下哪个按钮?

时间:2014-08-17 17:15:00

标签: html ajax button

<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js">
</script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){ 
        txtname=$("#btn1").val();
        $.ajax({url:"doSome.php",data:{name:txtname},success: function(ajaxresult){
            $("#ajaxrequest").html(ajaxresult);
        }});
    });
});
</script>
</head>
<body>
<button id="btn1" value="myButton">Click to send1</button>
<button id="btn2" value="myButton2">Click to send2</button>
<div id="ajaxrequest"></div>
</body>
</html>

如何识别按下哪个按钮:$(&#34;#btn1&#34;)。click(function(){ 无需再次为btn2写相同的代码?

3 个答案:

答案 0 :(得分:1)

您可以在所有按钮上使用选择器,然后在单击时取回ID

$('button').click(function()
{
   alert( $(this).attr('id') ); // Button ID clicked
});

答案 1 :(得分:0)

您可以使用

$( '#btn1' ).click(function(){
     submitForm( 'btnOne' );
}); 

$( '#btn2' ).click(function(){
     submitForm( 'btnTwo' );
}); 

然后在单个函数中传递参数:

function submitForm( type ){

    var dataString = $('#form_confirm_delete').serialize();
    dataString += "&type=" + type; 
    $.ajax({

          type: "POST",
          url: "doSome.php",
          data: dataString,
          dataType: 'json',
          cache: false,       
          success: (function(response) 
            {
                alert('Yes');
            })

     });
}

答案 2 :(得分:0)

实际上,只需使用多个选择器:

$('#btn1, #btn2').click(function(e) {
    var btn1Clicked = $(this).is('#btn1'); 
    var btn2Clicked = $(this).is('#btn2'); 
});