如何从javascript创建jQuery Mobile按钮

How do I create a jQuery Mobile button from javascript?

本文关键字:jQuery Mobile 按钮 创建 javascript      更新时间:2023-09-26

有没有办法让jQuery Mobile将javascript生成的链接呈现为按钮小部件,就像加载页面时自动执行的那样?

我有这样的javascript来动态创建链接:

var ws=document.getElementById('workspace'); // empty <div id="workspace"></div>
ws.innerHTML='<a id="myb" href="foo.php" data-role="button">baz</a>';

当然,它只生成一个普通的链接而不是一个按钮,所以我的问题是如何让jQueryMobile动态创建按钮,就像如果从一开始就在页面中出现相同的<a id="myb" href="foo.php" data-role="button">baz</a>一样?

编辑:

像这样的脚本:

$('#tagspace').html('<a id="myb" data-inline="true" data-ajax="false"
                    href="boo.php" data-role="button">baz</a>')
              .button()
              .click(function() { window.location.href=this.href;});

是一种改进。它确实会产生一个按钮(整页宽度),并且对标签文本之外的单击很敏感。但是,this似乎没有映射到包含预期链接"目标"的元素。

DOM 的结果是:

<div aria-disabled="false" class="ui-btn ui-shadow ui-btn-corner-all ui-fullsize
                                      ui-btn-block ui-btn-up-c" data-mini="false" data-inline="false" data-theme="c" data-iconpos="" data-icon="" data-wrapperels="span" data-iconshadow="true" data-shadow="true" data-corners="true"> <span class="ui-btn-inner ui-btn-corner-all">
        <span class="ui-btn-text">baz</span>
</span>
    <div aria-disabled="false" class="ui-btn-hidden" id="tagspace"> <a id="myb" data-inline="true" data-ajax="false" href="boo.php" data-role="button">baz</a>
    </div>
</div>

所以,它仍然不是同一种按钮。

您可以通过将元素包装在 jQuery 对象中并调用 button() 方法来创建按钮小部件。

$("#workspace").html("<a id='myb' href='foo.php' data-role='button'>baz</a>")
               .button();

更新:按钮小部件阻止链接的默认行为,因此如果您希望恢复该行为,则必须添加click处理程序:

$("#workspace").html("<a id='myb' href='foo.php' data-role='button'>baz</a>")
               .button()
               .click(function() {
                   window.location.href = this.href;
               });