Jquerymobile使用javascript创建按钮

时间:2012-09-17 17:21:41

标签: javascript button jquery-mobile

我正在尝试使用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);
});

1 个答案:

答案 0 :(得分:2)

您可以使用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/

相关问题