【问题标题】:Binding a jQuery event handler to multiple similar forms将 jQuery 事件处理程序绑定到多个类似的表单
【发布时间】:2011-11-03 14:40:50
【问题描述】:

我有一个 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。但是帽子会导致重复的代码。所以显而易见的想法是不要为每个项目重复类似的代码。

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

【问题讨论】:

    标签: javascript jquery events event-handling


    【解决方案1】:
    $('.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
    });
    

    【讨论】:

      【解决方案2】:

      在您的事件处理程序中,this 指的是被点击的特定元素。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-01
        • 2021-07-29
        • 1970-01-01
        • 2010-10-22
        • 1970-01-01
        • 1970-01-01
        • 2010-09-12
        相关资源
        最近更新 更多