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="Q29zdE1ldHJpY3MuYXNweD9Nb2RlbD0=" + 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 调用锚标记的点击事件


- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01