2014-03-05 83 views
0

我在我的HTML模板多个按钮单击事件处理程序

<div id="add"> 
    <fieldset> 
    </fieldset> 
    <input type="button" id="cancel" value="AddCancel"/> 
</div> 
<div id="update"> 
    <fieldset> 
    </fieldset> 
    <input type="button" id="cancel" value="UpdateCancel"/> 
</div> 

事件是有线了骨干,为按钮下面。我碰到的是,我必须连线AddCancel事件和UpdateCancel事件等等。

而不是布线每个取消按钮事件,有没有办法我可以有1 cancel按钮事件和处理程序,它可以识别哪个div被点击的取消按钮属于?

+4

ID必须是唯一,您的HTML无效。改为使用class。并回答你的问题:“是的,我们可以!” –

+1

为什么不只是为'AddCancel'和'UpdateCancel'分开事件,然后调用一个可重用的“Cancel”函数,允许您为两者重用相同的逻辑? –

回答

0

如果你想只有一个事件。首先确保你的html是正确的,它不能有两个具有相同ID的按钮。使用类代替

<div id="add"> 
    <fieldset> 
    </fieldset> 
    <input type="button" class="cancelbtn" id="btn1" value="AddCancel"/> 
</div> 
<div id="update"> 
    <fieldset> 
    </fieldset> 
    <input type="button" class="cancelbtn" id="btn2" value="UpdateCancel"/> 
</div> 

下一页使用此代码jQuery中

$(".cancelbtn").on("click", function(e){ 
    var buttonType = $(this).attr("value") 
    if(buttonType == "AddCancel"){ 
     //AddCancel Button Clicked 
    }else{ 
     //UpdateCancel Button Clicked 
    } 
}); 
0

你可以这样做:

var YourView ... 
    events: { 
     'click .cancel': 'cancel' 
    }, 

    cancel: function(event) { 
     var parent = event.currentTarget.parent(); // gets the parent of the clicked button 
     ... 
    } 
    ... 

和HTML:

<div id="add"> 
    <fieldset> 
    </fieldset> 
    <input type="button" class="cancel" value="AddCancel"/> 
</div> 
<div id="update"> 
    <fieldset> 
    </fieldset> 
    <input type="button" class="cancel" value="UpdateCancel"/> 
</div> 
相关问题