【问题标题】:Problem with fetching Id of the dynamically generated tag using jquery使用 jquery 获取动态生成的标签的 Id 的问题
【发布时间】:2011-06-11 07:50:31
【问题描述】:

我有以下函数来显示动态附加项目的标签的点击事件的 id。但是当执行该函数时,我的警报不显示 id,它弹出说未定义。请任何人都可以告诉哪里正是我错了。

这是我的功能

function getmenu()
     {
         $.ajax({
             type: "POST",
             url: "JsonWebService.asmx/GetMenus",
             data: "{}",
             contentType: "application/json; charset=utf-8",
             dataType: "xml",

             success:

                 function (results) {

                     $(results).find("Menu").each(function () {
                         var Text = $(this).find("Text").text();
                         var MenuId = $(this).find("MenuId").text();

                         var dmenu = $("#Menudiv");
                         dmenu.append("<td id='" + MenuId + "'><ul>" + Text + "</ul></td>");



                     });


                     $("#Menudiv").children('td').click(function () {

                         alert($(this).children('td').attr('MenuId'));

                     });


                 }
         });

    }

这将是我在 ajax 调用时生成的示例 xml 代码。

<ArrayOfMenu><Menu><MenuId>1</MenuId><Text>Books</Text></Menu><Menu><MenuId>2</MenuId><Text>Cd</Text></Menu><Menu><MenuId>3</MenuId><Text>Calendar</Text></Menu></ArrayOfMenu>

【问题讨论】:

    标签: javascript jquery xml ajax


    【解决方案1】:

    改变这一行:

    alert($(this).children('td').attr('MenuId'));
    

    到这里:

    alert($(this).attr('id'));
    

    这显示了 td 的 id。如果您打算检查 td 中的 ul - 并注意 ul 中没有 li 元素 - 您可以像上面那样使用“children”,但您需要更正您的 HTML (

      ...) 并相应地更改子选择器...或使用 find()... 取决于您实际尝试做什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多