javascript - 将 jQuery 事件处理程序绑定(bind)到多个相似的表单

标签 javascript jquery events event-handling

我有一个 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 事件处理程序绑定(bind)到该 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
});

关于javascript - 将 jQuery 事件处理程序绑定(bind)到多个相似的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7996757/

相关文章:

java - 在拖动 JSplitPane 分隔线时如何避免(或消耗)鼠标事件?

javascript - 我如何使用javascript代码隐藏div(使用php验证条件)

javascript - 所有测试文件中的 Jest Mock 用户模块

javascript - IE-8/IE-9 上的 Quickblox

javascript - 获取远程 jpg 图像的左上角像素颜色

javascript - 具有匿名函数的事件监听器(typeError,toggle undefined)

javascript - 如何通过消除双重等待和 DRY 代码进行重构?

javascript - 为什么 dirname 不是模块属性? (__ 符号)

jquery - Phonegap 应用程序的屏幕尺寸分辨率?

javascript - 传递 id 时,事件在 React Hooks 中不起作用。 TypeError : event. stopPropagation 不是一个函数