javascript 单击链接时如何运行脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17441650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run a script when clicking on a link?
提问by BrendanMann_1
So, I have a javascript for a popunder ad, (yeah I know they're annoying but it's not an ad, it's a page that opens behind the main page) anyway, because the script has the page open automatically when you go to my page, pop up blockers automatically block it, so what I would like to do is have the script run when someone clicks a link on my page, therefore it is user initiated and not automatically, so it doesn't get blocked by a popup blocker.. basically, so when someone clicks on one of the links on my page, it opens the link, but also opens the pop under behind my page.. I'm kind of new to javascript, but any help is appreciated!
所以,我有一个 popunder 广告的 javascript,(是的,我知道它们很烦人,但它不是广告,它是一个在主页后面打开的页面),因为脚本会在你转到我的页面时自动打开页面页面,弹出窗口阻止程序会自动阻止它,所以我想做的是在有人单击我页面上的链接时运行脚本,因此它是用户启动的而不是自动的,因此它不会被弹出窗口阻止程序阻止.. 基本上,所以当有人点击我页面上的一个链接时,它会打开链接,但也会打开我页面后面的弹出窗口.. 我是 javascript 新手,但感谢任何帮助!
回答by Matthias Holdorf
This would be one approach:
这将是一种方法:
HTML:
HTML:
<a id="link">Link</a>
JavaScript:
JavaScript:
function script() {
alert("I'm the ad");
};
document.getElementById('link').onclick = function () {
script();
};
For demonstration see this Fiddle.
有关演示,请参阅此Fiddle。
/Edit:Sure, here is the JavaScript:
/编辑:当然,这是JavaScript:
// copy and paste the script from the website
document.getElementById('open').onclick = function () {
load_pop_power();
};
If you don't want to show the ad when the user visits the site, you could however delete half of the code.
如果您不想在用户访问网站时显示广告,则可以删除一半的代码。
回答by blganesh101
You could do something like this
你可以做这样的事情
function doSomething() {
//do your actions here
window.location="http://www.gotothelink.com";
}
</script>
<a href="javascript:doSomething();">click me</a>
回答by TomWolk
When the user clicks the link, the javascript code in the "onlick" attribute is executed. "window.open" opens a new window and "return true" has the effekt that the normal behaviour of the link keeps working.
当用户点击链接时,“onlick”属性中的 javascript 代码被执行。“window.open”打开一个新窗口,“return true”具有链接的正常行为继续工作的效果。
<a href="http://www.tiscover.com" onclick="window.open('http://www.tiscover.com'); return true;">tiscover</a>
回答by Shaun Hare
So you need to bind the popunder to a click event on a link see http://www.pagecolumn.com/javascript/bind_event_in_js_object.htm
因此,您需要将 popunder 绑定到链接上的点击事件,请参阅http://www.pagecolumn.com/javascript/bind_event_in_js_object.htm