如何通过jquery模拟锚点单击?

时间:2023-01-23 21:14:45

I have a problem with faking an anchor click via jQuery: Why does my thickbox appear the first time I click on the input button, but not the second or third time?

我有一个通过jQuery伪造锚点的问题:为什么我的thickbox在第一次单击输入按钮时出现,而不是第二次或第三次出现?

Here is my code:

这是我的代码:

<input onclick="$('#thickboxId').click();" type="button" value="Click me" />

<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

It does always work when I click directly on the link, but not if I try to activate the thickbox via the input button. This is in FF. For Chrome it seems to work every time. Any hints?

当我直接点击链接时,它总是可以工作,但是如果我尝试通过输入按钮激活thickbox,它就不能工作。这是在FF。对于Chrome来说,它似乎每次都能运行。有提示吗?

17 个解决方案

#1


121  

Try to avoid inlining your jQuery calls like that. Put a script tag at the top of the page to bind to the click event:

尽量避免像这样内联jQuery调用。在页面顶部放置一个脚本标记,以绑定到单击事件:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        $('#thickboxId').click();
    });
});
</script>

<input id="thickboxButton" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Edit:

编辑:

If you're trying to simulate a user physically clicking the link, then I don't believe that is possible. A workaround would be to update the button's click event to change the window.location in Javascript:

如果你想模拟用户点击链接,那么我认为这是不可能的。解决方法是更新按钮的单击事件以更改窗口。位置在Javascript中:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        window.location = $('#thickboxId').attr('href');
    });
});
</script>

Edit 2:

编辑2:

Now that I realize that Thickbox is a custom jQuery UI widget, I found the instructions here:

现在我意识到Thickbox是一个自定义jQuery UI小部件,我在这里找到了说明:

Instructions:

  • Create a link element (<a href>)
  • 创建一个链接元素()
  • Give the link a class attribute with a value of thickbox (class="thickbox")
  • 给链接一个具有thickbox值的类属性(class="thickbox")
  • In the href attribute of the link add the following anchor: #TB_inline
  • 在链接的href属性中,添加以下锚:#TB_inline
  • In the href attribute after the #TB_inline add the following query string on to the anchor:

    在#TB_inline后的href属性中,将以下查询字符串添加到锚点:

    ?height=300&width=300&inlineId=myOnPageContent

    ? = 300宽度= 300 &inlineid = myOnPageContent高度

  • Change the values of height, width, and inlineId in the query accordingly (inlineID is the ID value of the element that contains the content you would like to show in a ThickBox.

    相应地更改查询中的高度、宽度和inlineId值(inlineId是包含要在ThickBox中显示内容的元素的ID值)。

  • Optionally you may add modal=true to the query string (e.g. #TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true) so that closing a ThickBox will require calling the tb_remove() function from within the ThickBox. See the hidden modal content example, where you must click yes or no to close the ThickBox.
  • 可以选择向查询字符串添加modal=true(例如:#TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true),以便关闭一个ThickBox将需要从ThickBox中调用tb_remove()函数。请参见隐藏模式内容示例,其中必须单击yes或no以关闭ThickBox。

#2


184  

What worked for me was:

对我起作用的是:

$('a.mylink')[0].click()

#3


19  

I've recently found how to trigger mouse click event via jQuery.

我最近发现了如何通过jQuery触发鼠标点击事件。

    <script type="text/javascript">
    var a = $('.path > .to > .element > a')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
    </script>

#4


8  

this approach works on firefox, chrome and IE. hope it helps someone:

这种方法适用于firefox、chrome和IE。希望它能帮助一些人:

var comp = document.getElementById('yourCompId');
try { //in firefox
    comp.click();
    return;
} catch(ex) {}
try { // in chrome
    if(document.createEvent) {
        var e = document.createEvent('MouseEvents');
        e.initEvent( 'click', true, true );
        comp.dispatchEvent(e);
        return;
    }
} catch(ex) {}
try { // in IE
    if(document.createEventObject) {
         var evObj = document.createEventObject();
         comp.fireEvent("onclick", evObj);
         return;
    }
} catch(ex) {}

#5


6  

The question title says "How can I simulate an anchor click in jQuery?". Well, you can use the "trigger" or "triggerHandler" methods, like so:

题目是“我如何在jQuery中模拟锚点单击?”你可以使用“触发器”或“triggerHandler”方法,比如:

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/thickbox.js"></script>
<script type="text/javascript">
$(function() {
    $('#btn').click(function() {
        $('#thickboxId').triggerHandler('click');
    })
})
</script>
...
<input id="btn" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Not tested, this actual script, but I've used trigger et al before, and they worked a'ight.

这个脚本没有经过测试,但是我以前用过触发器等,它们运行得很好。

UPDATE
triggerHandler doesn't actually do what the OP wants. I think 1421968 provides the best answer to this question.

UPDATE triggerHandler实际上并没有做OP想要的事情。我认为1421968年为这个问题提供了最好的答案。

#6


5  

I'd suggest to look at the Selenium API to see how they trigger a click on an element in a browser-compatible manner:

我建议查看Selenium API,看看它们如何以与浏览器兼容的方式触发对元素的单击:

Look for the BrowserBot.prototype.triggerMouseEvent function.

寻找BrowserBot.prototype。triggerMouseEvent函数。

#7


5  

Although this is very old question i found something easier to handle this task. It is jquery plugin developed by jquery UI team called simulate. you can include it after jquery and then you can do something like

虽然这是一个非常古老的问题,但我发现了一些更容易处理这个任务的方法。它是jquery UI团队开发的jquery插件,叫做模拟。您可以在jquery之后包含它,然后您可以做类似的事情

<a href="http://*.com/"></a>
$('a').simulate('click');

works fine in chrome, firefox, opera and IE10.you can download it from https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js

适用于chrome, firefox, opera和IE10。您可以从https://github.com/eduardolundgren/jquerysimulate/blob/master/jquery.simulate.js下载它

#8


4  

I believe you can use:

我相信你可以使用:

$('#yourLink').bind('click', function() {
  //Do something over here
});

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

This will easily trigger the click function, without actually clicking on it.

这将很容易地触发click函数,而无需实际单击它。

#9


2  

Do you need to fake an anchor click? From the thickbox site:

你需要假的锚点吗?从thickbox的站点:

ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).

可以从链接元素、输入元素(通常是按钮)和区域元素(图像映射)调用ThickBox。

If that is acceptable it should be as easy as putting the thickbox class on the input itself:

如果这是可以接受的,它应该像将thickbox类放在输入本身一样简单:

<input id="thickboxButton" type="button" class="thickbox" value="Click me">

If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.

如果不是,我建议使用Firebug,并在锚点元素的onclick方法中放置断点,看看它是否只在第一次单击时触发。

Edit:

编辑:

Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:

好吧,我必须为自己和我自己尝试一下,你的代码在Chrome和火狐上都很好用:

<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>

The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.

无论我点击输入还是锚元素,窗口都会弹出。如果上面的代码对您有效,我建议您的错误位于其他地方,并尝试隔离问题。

Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.

另一个可能是我们使用的是不同版本的jquery/thickbox。我正在使用从thickbox页面获得的信息—jquery 1.3.2和thickbox 3.1。

#10


2  

You can create a form via jQuery or in the HTML page code with an action that mimics your link href:

您可以通过jQuery或HTML页面代码创建一个表单,动作模仿您的链接href:

<a id="anchor_link" href="somepath.php">click here</a>.

<一个id = " anchor_link href=" somepath。php "> 点击这里< / >。

var link = $('#anchor_link').attr('href');
$('body').append('<form id="new_form" action="'+link+'"></form>');
$('#new_form').submit();

#11


2  

To simulate a click on an anchor while landing on a page, I just used jQuery to animate the scrollTop property in $(document).ready. No need for a complex trigger, and that works on IE 6 and every other browser.

为了在登陆页面时模拟单击锚点,我仅使用jQuery将$(document).ready中的scrollTop属性赋予动画效果。不需要复杂的触发器,这适用于IE 6和其他所有浏览器。

#12


2  

If you don't need to use JQuery, as I don't. I've had problems with the cross browser func of .click(). So I use:

如果您不需要使用JQuery,我不需要。我在.click()的跨浏览器func上遇到了问题。所以我使用:

eval(document.getElementById('someid').href)

#13


2  

In Javascript you can do like this

在Javascript中,可以这样做

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

你可以像这样使用它

submitRequest("target-element-id");

#14


1  

Using Jure's script I made this, to easily "click" as many elements as you want.
I just used it Google Reader on 1600+ items and it worked perfectly (in Firefox)!

使用Jure的脚本,我可以轻松地“单击”任意多的元素。我刚刚在1600多个条目上使用了谷歌阅读器,它运行得很好(在Firefox中)!

var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
$(selector).each(function(){this.dispatchEvent(e);});

#15


1  

JQuery('#left').triggerHandler('click'); works fine in Firefox and IE7. I haven't tested it on other browsers.

JQuery(#左).triggerHandler(“点击”);在Firefox和IE7中运行良好。我还没有在其他浏览器上测试过。

If want to trigger automatic user clicks do the following:

如要触发自动用户点击,请执行以下操作:

window.setInterval(function() 
    {
        $('#left').triggerHandler('click');
    }, 1000);

#16


0  

This doesn't work on android native browser to click "hidden input (file) element":

在android原生浏览器上,点击“隐藏输入(文件)元素”是行不通的:

$('a#swaswararedirectlink')[0].click();

But this works:

但是这个工作原理:

$("#input-file").show();
$("#input-file")[0].click();
$("#input-file").hide();

#17


0  

In trying to simulate a 'click' in unit tests with the jQuery UI spinner I could not get any of the previous answers to work. In particular, I was trying to simulate the 'spin' of selecting the down arrow. I looked at the jQuery UI spinner unit tests and they use the following method, which worked for me:

在尝试用jQuery UI spinner模拟“单击”单元测试时,我无法得到以前工作的任何答案。特别是,我试图模拟选择向下箭头的“自旋”。我查看了jQuery UI spinner单元测试,他们使用了以下方法,这对我很有用:

element.spinner( "widget" ).find( ".ui-spinner-up" ).mousedown().mouseup();

#1


121  

Try to avoid inlining your jQuery calls like that. Put a script tag at the top of the page to bind to the click event:

尽量避免像这样内联jQuery调用。在页面顶部放置一个脚本标记,以绑定到单击事件:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        $('#thickboxId').click();
    });
});
</script>

<input id="thickboxButton" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Edit:

编辑:

If you're trying to simulate a user physically clicking the link, then I don't believe that is possible. A workaround would be to update the button's click event to change the window.location in Javascript:

如果你想模拟用户点击链接,那么我认为这是不可能的。解决方法是更新按钮的单击事件以更改窗口。位置在Javascript中:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        window.location = $('#thickboxId').attr('href');
    });
});
</script>

Edit 2:

编辑2:

Now that I realize that Thickbox is a custom jQuery UI widget, I found the instructions here:

现在我意识到Thickbox是一个自定义jQuery UI小部件,我在这里找到了说明:

Instructions:

  • Create a link element (<a href>)
  • 创建一个链接元素()
  • Give the link a class attribute with a value of thickbox (class="thickbox")
  • 给链接一个具有thickbox值的类属性(class="thickbox")
  • In the href attribute of the link add the following anchor: #TB_inline
  • 在链接的href属性中,添加以下锚:#TB_inline
  • In the href attribute after the #TB_inline add the following query string on to the anchor:

    在#TB_inline后的href属性中,将以下查询字符串添加到锚点:

    ?height=300&width=300&inlineId=myOnPageContent

    ? = 300宽度= 300 &inlineid = myOnPageContent高度

  • Change the values of height, width, and inlineId in the query accordingly (inlineID is the ID value of the element that contains the content you would like to show in a ThickBox.

    相应地更改查询中的高度、宽度和inlineId值(inlineId是包含要在ThickBox中显示内容的元素的ID值)。

  • Optionally you may add modal=true to the query string (e.g. #TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true) so that closing a ThickBox will require calling the tb_remove() function from within the ThickBox. See the hidden modal content example, where you must click yes or no to close the ThickBox.
  • 可以选择向查询字符串添加modal=true(例如:#TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true),以便关闭一个ThickBox将需要从ThickBox中调用tb_remove()函数。请参见隐藏模式内容示例,其中必须单击yes或no以关闭ThickBox。

#2


184  

What worked for me was:

对我起作用的是:

$('a.mylink')[0].click()

#3


19  

I've recently found how to trigger mouse click event via jQuery.

我最近发现了如何通过jQuery触发鼠标点击事件。

    <script type="text/javascript">
    var a = $('.path > .to > .element > a')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
    </script>

#4


8  

this approach works on firefox, chrome and IE. hope it helps someone:

这种方法适用于firefox、chrome和IE。希望它能帮助一些人:

var comp = document.getElementById('yourCompId');
try { //in firefox
    comp.click();
    return;
} catch(ex) {}
try { // in chrome
    if(document.createEvent) {
        var e = document.createEvent('MouseEvents');
        e.initEvent( 'click', true, true );
        comp.dispatchEvent(e);
        return;
    }
} catch(ex) {}
try { // in IE
    if(document.createEventObject) {
         var evObj = document.createEventObject();
         comp.fireEvent("onclick", evObj);
         return;
    }
} catch(ex) {}

#5


6  

The question title says "How can I simulate an anchor click in jQuery?". Well, you can use the "trigger" or "triggerHandler" methods, like so:

题目是“我如何在jQuery中模拟锚点单击?”你可以使用“触发器”或“triggerHandler”方法,比如:

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/thickbox.js"></script>
<script type="text/javascript">
$(function() {
    $('#btn').click(function() {
        $('#thickboxId').triggerHandler('click');
    })
})
</script>
...
<input id="btn" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Not tested, this actual script, but I've used trigger et al before, and they worked a'ight.

这个脚本没有经过测试,但是我以前用过触发器等,它们运行得很好。

UPDATE
triggerHandler doesn't actually do what the OP wants. I think 1421968 provides the best answer to this question.

UPDATE triggerHandler实际上并没有做OP想要的事情。我认为1421968年为这个问题提供了最好的答案。

#6


5  

I'd suggest to look at the Selenium API to see how they trigger a click on an element in a browser-compatible manner:

我建议查看Selenium API,看看它们如何以与浏览器兼容的方式触发对元素的单击:

Look for the BrowserBot.prototype.triggerMouseEvent function.

寻找BrowserBot.prototype。triggerMouseEvent函数。

#7


5  

Although this is very old question i found something easier to handle this task. It is jquery plugin developed by jquery UI team called simulate. you can include it after jquery and then you can do something like

虽然这是一个非常古老的问题,但我发现了一些更容易处理这个任务的方法。它是jquery UI团队开发的jquery插件,叫做模拟。您可以在jquery之后包含它,然后您可以做类似的事情

<a href="http://*.com/"></a>
$('a').simulate('click');

works fine in chrome, firefox, opera and IE10.you can download it from https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js

适用于chrome, firefox, opera和IE10。您可以从https://github.com/eduardolundgren/jquerysimulate/blob/master/jquery.simulate.js下载它

#8


4  

I believe you can use:

我相信你可以使用:

$('#yourLink').bind('click', function() {
  //Do something over here
});

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

This will easily trigger the click function, without actually clicking on it.

这将很容易地触发click函数,而无需实际单击它。

#9


2  

Do you need to fake an anchor click? From the thickbox site:

你需要假的锚点吗?从thickbox的站点:

ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).

可以从链接元素、输入元素(通常是按钮)和区域元素(图像映射)调用ThickBox。

If that is acceptable it should be as easy as putting the thickbox class on the input itself:

如果这是可以接受的,它应该像将thickbox类放在输入本身一样简单:

<input id="thickboxButton" type="button" class="thickbox" value="Click me">

If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.

如果不是,我建议使用Firebug,并在锚点元素的onclick方法中放置断点,看看它是否只在第一次单击时触发。

Edit:

编辑:

Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:

好吧,我必须为自己和我自己尝试一下,你的代码在Chrome和火狐上都很好用:

<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>

The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.

无论我点击输入还是锚元素,窗口都会弹出。如果上面的代码对您有效,我建议您的错误位于其他地方,并尝试隔离问题。

Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.

另一个可能是我们使用的是不同版本的jquery/thickbox。我正在使用从thickbox页面获得的信息—jquery 1.3.2和thickbox 3.1。

#10


2  

You can create a form via jQuery or in the HTML page code with an action that mimics your link href:

您可以通过jQuery或HTML页面代码创建一个表单,动作模仿您的链接href:

<a id="anchor_link" href="somepath.php">click here</a>.

<一个id = " anchor_link href=" somepath。php "> 点击这里< / >。

var link = $('#anchor_link').attr('href');
$('body').append('<form id="new_form" action="'+link+'"></form>');
$('#new_form').submit();

#11


2  

To simulate a click on an anchor while landing on a page, I just used jQuery to animate the scrollTop property in $(document).ready. No need for a complex trigger, and that works on IE 6 and every other browser.

为了在登陆页面时模拟单击锚点,我仅使用jQuery将$(document).ready中的scrollTop属性赋予动画效果。不需要复杂的触发器,这适用于IE 6和其他所有浏览器。

#12


2  

If you don't need to use JQuery, as I don't. I've had problems with the cross browser func of .click(). So I use:

如果您不需要使用JQuery,我不需要。我在.click()的跨浏览器func上遇到了问题。所以我使用:

eval(document.getElementById('someid').href)

#13


2  

In Javascript you can do like this

在Javascript中,可以这样做

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

你可以像这样使用它

submitRequest("target-element-id");

#14


1  

Using Jure's script I made this, to easily "click" as many elements as you want.
I just used it Google Reader on 1600+ items and it worked perfectly (in Firefox)!

使用Jure的脚本,我可以轻松地“单击”任意多的元素。我刚刚在1600多个条目上使用了谷歌阅读器,它运行得很好(在Firefox中)!

var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
$(selector).each(function(){this.dispatchEvent(e);});

#15


1  

JQuery('#left').triggerHandler('click'); works fine in Firefox and IE7. I haven't tested it on other browsers.

JQuery(#左).triggerHandler(“点击”);在Firefox和IE7中运行良好。我还没有在其他浏览器上测试过。

If want to trigger automatic user clicks do the following:

如要触发自动用户点击,请执行以下操作:

window.setInterval(function() 
    {
        $('#left').triggerHandler('click');
    }, 1000);

#16


0  

This doesn't work on android native browser to click "hidden input (file) element":

在android原生浏览器上,点击“隐藏输入(文件)元素”是行不通的:

$('a#swaswararedirectlink')[0].click();

But this works:

但是这个工作原理:

$("#input-file").show();
$("#input-file")[0].click();
$("#input-file").hide();

#17


0  

In trying to simulate a 'click' in unit tests with the jQuery UI spinner I could not get any of the previous answers to work. In particular, I was trying to simulate the 'spin' of selecting the down arrow. I looked at the jQuery UI spinner unit tests and they use the following method, which worked for me:

在尝试用jQuery UI spinner模拟“单击”单元测试时,我无法得到以前工作的任何答案。特别是,我试图模拟选择向下箭头的“自旋”。我查看了jQuery UI spinner单元测试,他们使用了以下方法,这对我很有用:

element.spinner( "widget" ).find( ".ui-spinner-up" ).mousedown().mouseup();