1

我使用 jquery 1.3.2。我在一页中有 2 个具有相同 ID 的相同提交按钮。按钮具有不同的表单 ID。

两个按钮具有相同的 id

<input type="submit" id="edit-submit-43" class="form-submit">

两种形式都有不同的id

<form action="/productxy" accept-charset="UTF-8" method="post" id="uc-product-kit-add-to-cart-form-43-1" class="ajax-cart-submit-form"></form>

如何获取被点击的按钮形式的id,而不是html中第一个按钮?

4

2 回答 2

2

You don't show your JS, but assuming you are binding a common click handler to the buttons or a common submit handler to the forms you would use this in combination with DOM traversal methods:

$(".form-submit").click(function() {
    // assuming the button is actually inside its associated form:
    var parentFormID = $(this).closest("form").attr("id");
});

or:

$("form").submit(function() {
    var myId = this.id;
});

Within an event handler this will refer to the element that the event applied to.

And note that it is not valid to have duplicate IDs.

于 2013-06-08T00:15:10.313 回答
1

HTML 页面中的 ID 应该是唯一的。

将此更改为

<input type="submit" class="form-submit">

您可以完全删除idfor 按钮,因为它不是必需的

$('.form-submit').on('click', function() {

     var $form = $(this).closest('form');

     // this should give you the corresponding form 
     // in which the button is in

     var formId = $form.attr('id');
});
于 2013-06-08T00:12:12.380 回答