【发布时间】:2012-07-03 21:45:14
【问题描述】:
我正在创建一个 Windows Metro 应用程序,它以 ListViews 作为每个页面上的主要元素。我遇到了在页面之间导航的问题,特别是导航太快:单击一个页面上的 ListView 项目以转到另一个页面,然后单击新页面。当我这样做太快时,我会得到这个:
Exception was thrown but not handled in user code at line 20, column 13 in ms-appx://01c489fc-0e20-415d-ad4b-2895b4bc6e90/pages/groupedItems/groupedItems.js
0x800a138f - JavaScript runtime error: Unable to get property 'cloneNode' of undefined or null reference
If there is a handler for this exception, the program may be safely continued.
这是什么意思?是否有任何技术可以阻止这种异常并允许快速导航?
这是错误的代码:
function multisizeItemTemplateRenderer(itemPromise)
{
return itemPromise.then(function (currentItem)
{
var content;
// Grab the default item template used on the groupeditems page.
content = document.getElementById('multiTemplate');
/*************************
This line is where it fails:
*************************/
var result = content.cloneNode(true);
// Change the CSS class of the item depending on the group, then set the size in CSS.
switch (currentItem.groupKey)
{
case "1":
{
// Decides which item to resize based on items index
if (currentItem.index == 0 || currentItem.index == 1)
{
result.className = "largeitemtemplate"
}
else
{
result.className = "mediumitemtemplate"
}
break;
}
default:
{
result.className = "smallitemtemplate"
}
}
// Because we used a WinJS template, we need to strip off some attributes
// for it to render.
result.attributes.removeNamedItem("data-win-control");
result.attributes.removeNamedItem("style");
result.style.overflow = "hidden";
/************************
If this try catch isn't here, a RuntimeException occurs during quick navigation.
************************/
try{
result.getElementsByClassName("item-image")[0].src = currentItem.data.backgroundImage;
result.getElementsByClassName("item-title")[0].textContent = currentItem.data.title;
} catch (exception) {
console.log(exception.name + ": " + exception.message);
}
return result;
});
}
【问题讨论】:
-
您应该发布导致错误的代码。否则我能给出的最佳答案是您试图访问
undefined或null的.cloneNode属性 -
好的,我想我发布了问题代码。
-
您正在执行
document.getElementById('multiTemplate');,它返回null,因为找不到该元素。在浏览器脚本中,这意味着代码在 DOM 准备好之前运行,或者元素根本不存在此 ID。 -
@Esailija 那么如何确保 DOM 准备就绪?我还应该发布初始化我的布局的函数吗?
-
使用msdn.microsoft.com/en-us/library/windows/apps/hh868490.aspx 初始化您的应用程序。这里有更多关于此的提示,但更以 Metro 为中心msdn.microsoft.com/en-us/library/windows/apps/hh781221.aspx
标签: javascript microsoft-metro