更新--
我有一个“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/