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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/773639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:45:46  来源:igfitidea点击:

How can I simulate an anchor click via jquery?

jqueryhtmlonclickthickbox

提问by prinzdezibel

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 伪造锚点点击时遇到问题:为什么我第一次点击输入按钮时会出现粗框,但第二次或第三次没有?

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?

当我直接单击链接时,它总是有效,但如果我尝试通过输入按钮激活厚框则无效。这是在FF。对于 Chrome,它似乎每次都有效。任何提示?

采纳答案by John Rasch

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

尽量避免内联您的 jQuery 调用。在页面顶部放置一个脚本标记以绑定到click事件:

<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 clickevent to change the window.locationin Javascript:

如果您试图模拟用户实际单击链接,那么我认为这是不可能的。一种解决方法是更新按钮的click事件以更改window.locationJavascript:

<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")
  • In the hrefattribute of the link add the following anchor: #TB_inline
  • In the hrefattribute after the #TB_inlineadd the following query string on to the anchor:

    ?height=300&width=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.

  • 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.
  • 创建链接元素 ( <a href>)
  • 为链接指定一个值为thickbox ( class="thickbox")的类属性
  • href链接的属性中添加以下锚点:#TB_inline
  • href属性之后,#TB_inline将以下查询字符串添加到锚点:

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

  • 相应地更改查询中的 height、width 和 inlineId 的值(inlineID 是包含要在 ThickBox 中显示的内容的元素的 ID 值。

  • 或者,您可以将 modal=true 添加到查询字符串(例如#TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true),以便关闭 ThinBox 将需要tb_remove()从 ThickBox 中调用该函数。请参阅隐藏的模态内容示例,您必须在其中单击是或否以关闭厚框。

回答by Stevanicus

What worked for me was:

对我有用的是:

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

回答by Jure

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>

回答by damian

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) {}

回答by Ruwanka Madhushan

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://stackoverflow.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/jquery-simulate/blob/master/jquery.simulate.js下载它

回答by elo80ka

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 中模拟锚点点击?”。好吧,您可以使用“trigger”或“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 triggeret al before, and they worked a'ight.

未经测试,这个实际脚本,但我以前使用过trigger等,他们工作得很好。

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

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

回答by Sébastien RoccaSerra

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.triggerMouseEventfunction.

寻找BrowserBot.prototype.triggerMouseEvent功能。

回答by Deepak

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.

这将很容易触发点击功能,而无需实际点击它。

回答by Craig

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()。所以我使用:

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

回答by Yashpal Singla

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");