以编程方式单击jQuery Mobile应用程序中的链接

时间:2012-08-09 15:58:38

标签: jquery-mobile

我正在尝试以编程方式单击jQuery Mobile中的链接,但它无法正常工作。这是页面代码。

<section id="welcome" data-role="page">

<div class="content" data-role="content">
<a id="myLink"  href="http://www.google.de" target="_blank">The link</a>
<input type="button" id="launcher" value="Launch the link"/>
</div>
</section>

这是相应的javascript代码:

$(document).ready(function()
{
$("#launcher").bind("click",function()
{
    console.log("Inside the button click handler");
    $("#myLink").click();
});
});

看起来很简单,但我似乎可以使它工作。感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

它不起作用的一个可能原因是DOM中有另一个<a id="myLink"></a>,但不在活动页面中。如果是这种情况,您的代码可能会触发该元素上的单击处理程序而不是您在屏幕上看到的单击处理程序。也许使用$.mobile.activePage.find("#myLink").click();会有效。

另外,you should avoid using $(document).ready() in jQuery Mobile

答案 1 :(得分:0)

这个问题并不是真正的答案,但如果您只想实现要启动的链接(并且您不想执行您为链接定义的点击处理程序,如果有的话),这可以是一个解决方案

$(document).ready(function()
{
$("#launcher").bind("click",function()
{
    console.log("Inside the button click handler");
    window.open($("#myLink").attr("href"),$("#myLink").attr("target"));
});
});

答案 2 :(得分:0)

您应该使用触发器,如下所示:

$('#mylink').trigger('click');

另外,检查你的绑定实际上是绑定到一个元素。在JQM中,您不应该依赖$(document).ready。而是使用$(document).bind('pageinit')。见here

答案 3 :(得分:0)

我遇到了同样的问题。 对我有用的是在DOM对象本身上调用click()。只需在jQuery对象之后添加“[0]”。

像这样:

$(document).ready(function()
{
$("#launcher").bind("click",function()
{
    console.log("Inside the button click handler");
    $("#myLink")[0].click();
});
});