使用jQuery .click()(或类似)在href属性中触发javascript [英] Trigger javascript in href attribute with jQuery .click() (or similar)
问题描述
不幸的是,我正在使用一些第三方javascript,它会在我的网页中插入链接。我不想直接使用这些链接,而是使用代理元素,当点击它时,会触发第三方链接上的点击事件。
Unfortunately, I'm working with some 3rd party javascript, which inserts links into my pages. Rather than just use these links as is, I want to use proxy elements, which, when clicked, trigger the click event on the 3rd party links.
第三方链接将javascript打包到href属性中,如下所示:
The 3rd party links pack javascript into the href attribute, like this:
<a id="horribleLink" href="javascript:doSomething()">Click me</a>
我的代理元素如下所示:
My proxy element looks like this:
<button rel="horribleLink" class="linkProxy">No, click me</button>
还有一些jQuery的javascript将它们链接在一起:
And a bit of jQuery'd javascript to link them together:
$('button.linkProxy').click(function(){
$('#' + $(this).attr('rel')).click();
});
现在,如果第三方链接只是一个标准链接(稍微不那么可怕onclick(< a id =horribleLinkhref =http://www.google.com>点击< / a>
)或< a href =#id =horribleLinkonclick =doSomething()>点击< / a>
),但当javascript在里面时href属性,触发'click'什么都不做。
Now, this works perfectly if the 3rd party link is just a standard link ( a slightly less horrible onclick (<a id="horribleLink" href="http://www.google.com">Click</a>
), or<a href="#" id="horribleLink" onclick="doSomething()">Click</a>
), but when the javascript is inside the href attribute, triggering 'click' does nothing at all.
任何人都可以告诉我原因,以及是否有合理的解决方法?
Can anyone tell me why, and if there's a reasonable workaround?
已更新正如Millimetric所说,根本原因似乎是浏览器阻止了对锚点的伪造点击 - 我删除了我的标准链接示例,因为这是另一种情况,不起作用。然而,onclick处理程序确实可以正常工作。
Updated As Millimetric said, the root cause looks to be that browsers prevent 'faking clicks' on anchors - I've removed my 'standard link' example, as that's another situation that doesn't work. The onclick handler does work, though, as you'd expect.
推荐答案
这里接受的答案有点深入为什么会发生这种情况:我可以调用jquery click()来跟随< a>链接,如果我没有使用绑定或点击已绑定事件处理程序?。基本上,似乎你不能在链接上执行click(),因为浏览器不支持虚假点击。
The accepted answer here goes into a little depth as to "why this is happening": Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?. Basically, it seems you can't do a click() on a link because the browser doesn't support fake clicking.
一个解决方法:
如果为这些情况设置了location.href,它可以工作:
If you set location.href for those cases, it works:
$('button.linkProxy').click(function(){
location.href = $('#' + $(this).attr('rel')).attr('href');
});
工作小提琴: http://jsfiddle.net/uv29x/3/
两种解决方法:
你可以得到这些链接的href并对它们做一个 eval()
,对吗?
You could just get the href of those links and do an eval()
on them, right?
这篇关于使用jQuery .click()(或类似)在href属性中触发javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!