繁体   English   中英

将jQuery事件处理程序绑定到多种相似形式

[英]Binding a jQuery event handler to multiple similar forms

我有一个带有多个类似元素的html页面,可以就地对其进行编辑:

The Title
Some description
Count 10
[Edit]

Another Title
Another description
Count 54
[Edit]

...

如果单击编辑按钮,则文本将通过Ajax替换为表单(页面的其余部分将不会重新加载):

Title:       [The Title       ]
Description: [Some description]
Count:       [10]
[Save] [Cancel]

Another Title
Another description
Count 54
[Edit]

...

对于所有项目,用表格替换文本并提交表格的事件处理程序几乎相同。 我的第一种方法是在html标记中使用ID,并将jQuery事件处理程序绑定到该ID。 但是帽子会导致重复的代码。 因此,显而易见的想法是不要为每个项目重复类似的代码。

如何在事件处理程序中区分项目,以便用表单替换正确的项目并提交正确的表单?

$('.classYouPutOnAllEditButtons').click(function () {
    var that = $(this); // this variable now holds a reference to the Edit button that was clicked, you can use a traversal method (e.g. closest()) to find the form it was in
    // do your other stuff
});

在事件处理程序内部, this是指被单击的特定元素。

$(yourSelector).bind('event', function () {
    // in here, `this` will be the Edit button.
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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