javascript - jquerymobile 使用 javascript 创建按钮

标签 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);
});

最佳答案

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

相关文章:

javascript - $routeChangeSuccess 不适用于 ngNewRouter AngularJS 1.4

javascript - Angular - 正确嵌套 Observables 及其订阅

android - 使用 jquery mobile 和 phonegap 在 android 4.0 webview 中聚焦时创建输入字段的副本

c# - 如何在 WPF 中使按钮内的网格具有 100% 的宽度?

jquery - JavaScript 执行超出超时 - jQuery mobile

javascript - 使用固定位置的数据过滤器(不可滚动)

javascript - 目标 =“_blank” 在 Chrome 中不起作用?

javascript - AngularJS 破坏了 JQuery 动画

c# - WPF 按钮打开或关闭彩色状态

android - 如何在应用程序中添加通知徽章?