JavaScript: Invoking click-event of an anchor tag from javascript(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 调用锚标记的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript:从 javascript 调用锚标记的点击事件


基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01