使用.closest从td获取值并不会给出价值

时间:2017-09-08 01:15:14

标签: javascript jquery

我像这样创建表:

<table class="table" id="tbl_items">
<thead>
    <tr>
        <th>
            Id
        </th>
        <th>
            Item
        </th>
        <th>
            Serial Key
        </th>
        <th>
            Brand
        </th>
        <th>
            Quantity
        </th>
        <th>
            Description
        </th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model)
    {
        ViewBag.AccountID = item.AccountId.ToString();
        if (item.Items != null)
        {
            foreach (var itemOnList in item.Items)
            {
                <tr>
                    <td class="cls-itemid" data-itemid="@itemOnList.ItemId">@Html.DisplayFor(model => itemOnList.ItemId)</td>
                    <td class="cls-itemname" data-itemname="@itemOnList.ItemName">@Html.EditorFor(model => itemOnList.ItemName)</td>
                    <td class="cls-serialnumber" data-serialnumber="@itemOnList.SerialNumber">@Html.EditorFor(model => itemOnList.SerialNumber)</td>
                    <td class="cls-brandname" data-brandname="@itemOnList.BrandName">@Html.EditorFor(model => itemOnList.BrandName)</td>
                    <td class="cls-quantity" data-quantity="@itemOnList.Quantity">@Html.EditorFor(model => itemOnList.Quantity)</td>
                    <td class="cls-description" data-description="@itemOnList.Description">@Html.EditorFor(model => itemOnList.Description)</td>
                    <td>
                        <a href="javascript:void(0);" data-itemid="@itemOnList.ItemId" class="btn_edit">Edit |</a>
                        <a href="javascript:void(0);" data-itemid="@itemOnList.ItemId" class="btn_delete">Delete</a>
                    </td>
                </tr>
            }
        }
    }
</tbody>

我试图使用这个来连续获取td的值:

$(".btn_edit").click(function() {
    var row = $(this).closest("tr");
    var text = row.find(".cls-itemname").text();
    alert(text);
});

警告框没有值。我无法使用数据项,因为当我更改@ Html.EditorFor框的值时,它会提供旧值而不是新值。

1 个答案:

答案 0 :(得分:2)

由于您使用@Html.DisplayFor()会返回<input>元素...我想您想要输入文字...

这将有效:

$(".btn_edit").click(function() {
  var row = $(this).closest("tr");
  var text = row.find(".cls-itemname input").val();  // <-- Look the change here
  alert(text);
});

.cls-itemname元素中根本没有文字......但input有一个value。对input使用.val()