JavaScript:从 javascript 调用锚标记的点击事件 [英] JavaScript: Invoking click-event of an anchor tag from javascript

查看:20
本文介绍了JavaScript:从 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.

请多多指教.提前致谢.

Kindly advise. Thanks in advance.

推荐答案

如果你安装了 jQuery,那么为什么不这样做呢:

If you have jQuery installed then why not just do this:

$('#proxyAnchor')[0].click();

请注意,我们使用 [0] 来指定第一个元素.jQuery 选择器返回一个 jQuery 实例,并在其上调用 click() 仅调用 click javascript 处理程序,而不是 href.在实际元素(由 [0] 返回)上调用 click() 将遵循 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.

请参阅此处的示例来说明差异: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆