JavaScript:从javascript中调用锚定标记的点击事件 [英] JavaScript: Invoking click-event of an anchor tag from javascript
问题描述
我有一个含有锚定标签的网页。在我的JavaScript中,我根据一些if-else条件动态设置锚标记的 HREF
属性。现在我想以编程方式调用锚标记的点击事件。我使用以下代码,但是不成功。
I have a page with an anchor tag. In my JavaScript I am setting the HREF
attribute of the anchor tag dynamically based on some if-else conditions. Now I want to invoke the click event of the anchor tag programmatically. I used the below code, but was not successful.
var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650";
document.getElementById("proxyAnchor").href=proxyImgSrc;
document.getElementById("proxyAnchor").onclick;
任何人都可以告诉我如何继续?我在这个链接上有一个jQuery灯箱实现(thickbox)。
Can any one tell me how to go ahead? I have a jQuery light box implementation(thickbox) on this link.
请教一下。提前感谢。
推荐答案
如果您安装了jQuery,那么为什么不要这样做:
If you have jQuery installed then why not just do this:
$('#proxyAnchor')[0].click();
请注意,我们使用[0]指定第一个元素。 jQuery选择器返回一个jQuery实例,并调用click()只调用单击javascript处理程序,而不是href。在实际元素上调用click()(由[0]返回)将在href等中的链接之后。
Note that we use [0] to specify the first element. The jQuery selector returns a jQuery instance, and calling click() on that only calls click javascript handler, not the href. Calling click() on the actual element (returned by [0]) will follow the link in an href etc.
请参见这里举例说明区别: a href =http://jsfiddle.net/8hyU9/ =nofollow noreferrer> http://jsfiddle.net/8hyU9/
See here for an example to illustrate the difference: http://jsfiddle.net/8hyU9/
至于为什么你的原始代码不工作 - 这可能是因为你正在调用 onclick
,而不是 onclick()
。没有括号JavaScript将返回任何分配给 onclick
属性的值,而不尝试执行它。
As to why your original code is not working - it is probably because you are calling onclick
, and not onclick()
. Without the parenthesis JavaScript will return whatever is assigned to the onclick
property, not try to execute it.
下面的简单示例来看看我的意思:
Try the following simple example to see what I mean:
var f = function() { return "Hello"; };
alert(f);
alert(f());
第一个将显示函数的实际文本,第二个将显示Hello如预期。
The first will display the actual text of the function, while the second will display the word "Hello" as expected.
这篇关于JavaScript:从javascript中调用锚定标记的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!