我有一个 html 页面,其中有许多 jquery 移动面板。现在我需要从 javascript 动态创建新面板。所有面板都位于具有特定 id 的 div 中。我使用 getElementById 而不是 innerHtml 在运行时附加新的 div。
问题是 jquery div 不应该出现,直到我单击打开它的链接。但是当我从 javacript 中获取 jquery div 时,它显示为普通 div。 jquery 移动脚本似乎无法识别我在运行时添加的新 div。 谁能帮助我吗?
非常感谢。
这是问题的一个简单示例:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div id="panels">
<div data-role="panel" id="myPanel">
<h2>Panel Header</h2>
<p>You can close the panel by clicking outside the panel, pressing the Esc key or by swiping.</p>
</div>
</div>
<a href="#myPanel" class="ui-btn ui-btn-inline ui-corner-all ui-shadow">Open Panel</a>
<a href="#myPanel2" class="ui-btn ui-btn-inline ui-corner-all ui-shadow">Open Panel2</a>
</body>
<script type="text/javascript">
//now when an event is verified i inner the new jquery mobile panel
e.addEventListener("click", function(){
document.getElementById("panels").innerHTML+=' <div data-role="panel" id="myPanel2">
<h2>Panel Header</h2>
<p>Text</p>
</div>';
}, false);
</script>
</html>
最佳答案
动态添加面板后,您需要告诉 jQuery Mobile 对其进行初始化。一种方法是在面板容器上调用enhanceWithin():
$("#btnAdd").on("click", function () {
var panel = '<div data-role="panel" id="myPanel2"><h2>Panel Header</h2><p>Text</p></div>';
$("#panels").append(panel).enhanceWithin();
});
另一种方法是直接在新添加的面板 div 上调用 panel() 小部件初始值设定项;
$("#btnAdd").on("click", function () {
var panel = '<div data-role="panel" id="myPanel2"><h2>Panel Header</h2><p>Text</p></div>';
$("#panels").append(panel);
$("#myPanel2").panel();
});
关于javascript - Jquery mobile,从 javascript 动态添加面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30582323/