javascript - 如何从 js 文件(使用 ASP.NET MVC 5、Kendo-UI)访问部分 View 中的元素(通过 AJAX 调用加载)?

标签 javascript html kendo-asp.net-mvc asp.net-mvc-partialview kendo-template

更新--

我有一个“index.js”,该脚本在 Index.cshtml 中呈现。 Index.cshtml 有一个 <div id="main"> *KendoPanelBar here* </div> 我成功地将部分 View 加载到 main-div 的面板中。

“MyPartialView.cshtml”具有:<div id="menu"></div>

在index.js中,我尝试 console.log($("#menu"));

输出是一个长度为 0 的 jQuery 对象。 'MyPartialView.cshtml' 与 'Index.cshtml' 位于同一文件夹中('Index.cshtml' 中的元素可以成功输出)。

正如 @Guillaume 评论的那样:脚本必须在 View 呈现后运行!

<小时/>

我的实际目标是将 KendoMenu 动态放入 div 菜单中,该菜单位于 MyPartialView 中的 KendoTemplate 中。 为了获取 MyPartialView,我做了:

mainDiv.append({
            text: "Group1",
            encoded: false,
            contentUrl: "\MyPartialView"  //that successfully put the partial view where I want it
        });

正如 @Rory 评论的那样,我必须在 AJAX 调用成功时/之后访问 MyPartialView 中的元素。

因此,我改变了contentUrl:...content: '<div id="partialHere"><div>'并尝试将部分 View 加载到该 div 中:

   $.ajax({
        type: "POST",
        url: myUrl,
        success: function (partialView) {
            $("#menu").kendoMenu({ //does not apply
            dataSource: [{
            text: "<span class=\"k-icon k-i-more-horizontal\"></span>", encoded: false, items: [
                { text: "<span class=\"k-icon k-i-edit\"></span><span>Edit</span>", encoded: false },
                   ]
                 }]
             });
            //dosth
            $("#groupContent").html(partialView); //adding PartialView to DOM
            console.log($("#menu")); //even after adding to DOM, the output is a jQuery-object with length of 0
        }
    });

partialView 按原样加载到 div 中。但我对菜单 div 所做的更改并不适用。

我做错了什么?

最佳答案

这里的顺序很重要。在尝试查询之前添加 html。

//dosth
$("#groupContent").html(partialView);

// Partial View has been added to the DOM. Now it is accessible to jQuery  
$("#menu").kendoMenu({ //does not apply
  dataSource: [{
    text: "<span class=\"k-icon k-i-more-horizontal\"></span>",
    encoded: false,
    items: [{
      text: "<span class=\"k-icon k-i-edit\"></span><span>Edit</span>",
      encoded: false
    }, ]
  }]
});

关于javascript - 如何从 js 文件(使用 ASP.NET MVC 5、Kendo-UI)访问部分 View 中的元素(通过 AJAX 调用加载)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53079993/

相关文章:

javascript - Cakephp 3.6.14 : Make datetime field readonly

javascript - 使用 css3 滑动图像

html - 在视频(iframe 或对象)上显示 div

css - kendo 下拉列表在页面呈现时显示选定的值

jquery - 如何居中 Kendo 窗口?

javascript - 跨域iframe通信

javascript - 如果函数来自外部 JavaScript 库,如何处理 JavaScript 中的函数名称冲突?

html - css - 如何隐藏嵌套在 div 中的 href 链接?

javascript - setInterval ("/*some code*/", time) 和 setInterval(function() {/*一些代码*/}, time)

javascript - 如何将事件添加到 Kendo UI Scheduler?