0

我必须使用jquery来显示对话框,但有一个问题,我有多个名称相似的按钮,例如:btnEditUser-1、btnEditUser-2、btnEditUser-3

我必须为每个按钮调用相同的函数才能调用 AJAX 函数。

请建议我该怎么做?

请查找 html/javascript 代码以供参考:

cakephp代码打印html

if($user['id']=="1" or ((strtotime(date("Y-m-d"))-strtotime($searchres[$i]['documents']['uploadtime']))<172800))
    {

    echo $this->Form->button('Edit User', array('type'=>'button','id'=>'edituser-'.$id,'name'=>'edituser-'.$id,'value'=>$id));
}

我必须在 jquery 中编写以下函数来接收按钮发送的值(如上所述):

function showedituser(doc_id) {
        var data = {doc_id : doc_id};
        var divname = $('#dialog-edituser');
        $("#dialog-markup").dialog("open");
        var url = 'documents/getassigned_users';
        callajax(url, data, divname);
        return false;
   }
4

1 回答 1

2

为所有这些按钮添加一个公共类。例如:

<input type="button" id="btnEditUser-1" class="btnEditUser" >
<input type="button" id="btnEditUser-2" class="btnEditUser" >
.......................
<input type="button" id="btnEditUser-n" class="btnEditUser" >

然后为所有这些添加一个单击处理程序(例如使用 jQuery):

$('.btnEditUser').on('click', function(event){
    //If you're in a form you may want to prevent the default behaviour (sumbit the form)
    event.preventDefault();
    //Now most-probably you'd like to do something different for each button clicked:
    var buttonIdParts = $( this ).attr('id').split('-');
    //Now you're left with the number from the id
    var buttonId = buttonIdParts[1];
    switch(buttonId)
    {
    case 1:
       // execute code block 1
       //AJAX Call, whatever
        break;
    case 2:
      //  execute code block 2
        break;
    default:
    //code to be executed if n is different from case 1 and 2
    }
});

除了解析之外,id您还可以使用数据属性

<input type="button" id="btnEditUser-1" class="btnEditUser" data-button-id="1">
<input type="button" id="btnEditUser-2" class="btnEditUser" data-button-id="2">
...............
<input type="button" id="btnEditUser-n" class="btnEditUser" data-button-id="n">

并直接获取正确的 id:

//This goes inside the events handler
var buttonId = $( this ).attr('data-button-id');

同样重要的是要注意,在事件处理程序回调函数中,上下文this是刚刚单击的按钮,并且$( this )是 jQuery 选择此按钮(从 DOM 中)并从中创建一个jQuery 对象

于 2013-06-13T06:46:31.577 回答