簡體   English   中英

jQuery 在單擊按鈕時獲取最接近的表單

[英]jQuery get closest form on button click

我想在按下表單按鈕時發出ajax請求我需要獲取表單本身我的代碼是

$(document).ready(function() {
        $(document).on('click', '.finalEdit', function (e) {
            e.preventDefault();
            var form = $(this).closest('form');
            $.ajax({
                data: form.serialize(),
                url: form.attr('action'),
                type: "POST",
                dataType: "html",
                success: function (result) {
                    // feel free to execute any code 
                    // in the success callback
                    $('#divToRefresh').html(result);
                },
                error: function (result) {
                alert("Failed");
            }
            })

            return false;
        });

$(this).closest('form') 在頁面中獲取另一個表單我不知道為什么

這是我要找的表格

<tr hidden="hidden">
            @using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { @class = "Edit-form" }))
            {
                @Html.ValidationSummary(true)
                <td>
                    @Html.HiddenFor(model => model.supplier.SupplierID, new { @Value = item.SupplierID })
                </td>
                <td>
                    @Html.TextBoxFor(model => model.supplier.SupplierName, new { @Value = item.SupplierName })
                </td>
                <td>
                    <input type="submit" value="Edit" class="finalEdit"/>
                </td>



            }
        </tr>

如果.finalEdit按鈕在表單標簽內,您可以使用this.form獲取元素所屬的表單。 然后,您可以將其包裝在$()中以獲取表單元素的 jQuery 對象: var form = $(this.form); .

如果未找到表單,請確保標簽已正確嵌套和閉合。 還要確保輸入沒有form屬性

$(this).closest('form')沒有得到另一種形式。 它實際上沒有得到任何形式。

我不知道為什么.closest('form')在那種情況下不起作用

無論如何,這行代碼對我有用

var form = $(this).parent().parent().children(":first");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM