【问题标题】:When I append to an HTML table using jquery I can't trigger the table row click event当我使用 jquery 附加到 HTML 表时,我无法触发表行单击事件
【发布时间】:2020-03-12 23:56:12
【问题描述】:

我正在使用 asp.net mvc。我正在尝试使用 jquery 附加到 HTML 表。我从 getJSON 调用中获取行并将它们附加到表中。行已附加,但由于某种原因,添加的行不会触发点击事件。我想可能是因为时间或其他原因,但我不确定。

控制器

using System;
using System.Web;
using System.Web.Mvc;

namespace Test
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Test(string x)
        {
            string strJson = "[{\"name\":\"tom\",\"number\":\"111\"},{\"name\":\"bill\",\"number\":\"222\"}]";
            return Json(strJson, JsonRequestBehavior.AllowGet);
        }

    }
}

查看

@{
    Layout = null;
}

<style>
    td {
        border: 2px solid black;
    }
</style>

<br />
<br />

<table id="table1">
    <tr>
        <td>
            name
        </td>
        <td>
            number
        </td>
    </tr>
</table>

<br />
<br />

<button id="button1" type="button">append rows</button>

<script src="~/Scripts/jquery-3.4.1.js"></script>

<script>

    //table click event
    $(document).ready(function () {

        $("#table1 tr").click(function () {

            alert("table row clicked");

        });

    });

    //button click event
    $(document).ready(function () {

        $("#button1").click(function () {

            $.getJSON('@Url.Action("Test")', { x: "1" }, function (y) {

                y = $.parseJSON(y);

                $.each(y, function (i, item) {

                    $('#table1').append('<tr><td>' + item.name + '</td><td>' + item.number + '</td></tr>');

                });

            });

        });

    });

</script>

【问题讨论】:

    标签: c# jquery html asp.net-mvc


    【解决方案1】:

    未触发该事件,因为该行是在附加事件处理程序之后添加的。使用:

    $(document).on("click", "#table1 tr", function (){}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多