获取刚刚点击的按钮用户的ID

时间:2016-03-12 18:53:54

标签: jquery ajax

在询问之前,我已经检查了How to get ID of button user just clicked?这个问题。

我正在尝试获取按钮的ID。以下是代码。

<form name="edit_posting1" id="edit_posting1" method="post" action="edit_posting_bk.php" role="form">

<center>

<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview"/>
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')"  alt="Save" value="Save"/>
<?php
if($disable == true){
    echo '<input class="btn btn-home" type="submit" name="disable" id="disable" alt="Disable" value="Disable"/>';
}else{
    echo '<input class="btn btn-home" type="submit" name="enable" id="enable" alt="Enable" value="Enable"/>';
}
?>
</center>

Ajax代码

<script type="text/javascript">
    $("#edit_posting1").on("submit", function(e) {
        e.preventDefault;
        var btn = $('#publish');
        //var el = 'publish';
        var el = $(btn).attr('id');
        alert(el);
    })
</script>

根据我对Ajax代码的理解问题。有人可以就此提出建议吗?

谢谢

注意:我想要的是如果用户点击启用/禁用或发布按钮,我会得到按钮的ID或名称。

3 个答案:

答案 0 :(得分:2)

如果您想在submit button上获得form submit被按下的ID,可以listening点击其中一个,然后保存id in variable,然后access that variable in form submit event handler
请查看以下代码段

&#13;
&#13;
 var subm = "";
 $('input[type="submit"]').click(function(e) {
   subm = e.target.id;
 });


 $("#edit_posting1").on("submit", function(e) {
   e.preventDefault();
   var el = subm;
   alert(el);
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="edit_posting1" id="edit_posting1" method="post" action="edit_posting_bk.php" role="form">

  <center>

    <input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview" />
    <input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save" />
    <?php if($disable==t rue){ echo '<input class="btn btn-home" type="submit" name="disable" id="disable" alt="Disable" value="Disable"/>'; }else{ echo '<input class="btn btn-home" type="submit" name="enable" id="enable" alt="Enable" value="Enable"/>'; }
    ?>
  </center>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尽量不要污染全局范围而不是使用.data()

 $("#edit_posting1").on("submit", function(e) {
   e.preventDefault();
   var el = $(this).data('submitter');
   alert(el);
 });

 $("#publish,#save").click(function(e) {
   if (this.id == "save") {
     if (!confirm('Are you sure you want to Submit.')) {
       e.preventDefault();
       return false;
     }
   }
   $(this).closest("#edit_posting1").data("submitter", this.id);
 });

DEMO

答案 2 :(得分:0)

尝试这种方式 -

<script type="text/javascript">
    $(function () {
        $('.btn-home').on('click', function (e) {
            e.preventDefault();
            var id = $(this).attr('id');
            alert(id);
        });
    });
</script>