我正在尝试使用 javascript 创建 href,它应该有 data-role="button"。但是按钮没有显示。这是我的代码。
var a = document.createElement("A");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
我将它附加到 div 作为子元素,我可以看到文本,而且 onClick 参数也很好用。但由于某种原因,它没有显示为按钮,而是显示为 normaln href。关于如何使用 JS 动态创建 jquerymobile 按钮的任何建议?这是完整的代码:
$(document).ready(function(){
var a = document.createElement("A");
var div = document.createElement("div");
var span = document.createElement("span");
var p2 = document.createElement("p");
var p = document.createElement("p");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
div.setAttribute("id","alertMessage");
span.appendChild(document.createTextNode("Pripojenie zlyhalo"));
p2.setAttribute("style","text-align: center;");
span.setAttribute("class","red");
p.appendChild(span);
p.appendChild(document.createTextNode(" (skontrolujte nastavenia siete)."));
div.appendChild(p);
p2.appendChild(a);
div.appendChild(p2);
var mainDiv = document.getElementById("alert");
mainDiv.appendChild(div);
$('mainDiv').trigger('create');
var toppos=($(window).height()/2) - ($("#alertMessage").height()/2);
var leftpos=($(window).width()/2) - ($("#alertMessage").width()/2);
$("#alertMessage").css("top", toppos).css("left",leftpos);
});
最佳答案
您可以使用 trigger('create')
应用所有 jQuery Mobile 格式。完整的工作代码:
HTML:
<div id="container"></div>
JavaScript:
var a = document.createElement("A");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
$('#container').append(a).trigger('create');
这可以在这里看到:http://jsfiddle.net/sQ2dA/ .
针对您的编辑:问题是您在引号中包含 mainDiv
,因此您在这一行传递了一个字符串:
$('mainDiv').trigger('create');
但是你应该传递变量mainDiv
:
$(mainDiv).trigger('create');
请在此处查看工作示例:http://jsfiddle.net/P62Cp/ .
关于javascript - jquerymobile 使用 javascript 创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464206/