javascript html:点击链接时执行函数,获取警报,然后重定向到另一个页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21829351/
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
html: execute function when link clicked, get alert and then redirect to another page
提问by Haradzieniec
What's the best way to combine two strings
组合两个字符串的最佳方法是什么
String 1:
字符串 1:
<a href="javascript:myFunc();" onclick="alert('myFunc executed')">Click here</a>
and String 2:
和字符串 2:
<a href="http://google.com">click here</a>
so that:
myFunc() executed;
alert appears;
once alert is clicked, the page is being redirected to http://google.com
这样: myFunc() 执行;出现警报;单击警报后,页面将被重定向到http://google.com
I'm asking about the most correct way to do that.
我问的是最正确的方法来做到这一点。
Thank you.
谢谢你。
回答by Maksim Gladkov
Use:
利用:
<a href="http://google.com" onclick="myFunc(); alert('myFunc executed'); return true">click here</a>
回答by BJ Safdie
Your approach is very "obtrusive" JavaScript. Nowadays, folks tend to recommend an Unobtrusive JavaScriptapproach.
你的方法是非常“突兀”的 JavaScript。如今,人们倾向于推荐Unobtrusive JavaScript方法。
<a id="myLink" href="http://google.com" data-message="myFunc executed">Click Here</a>
Note that there is no JavaScript in the HTML.
请注意,HTML 中没有 JavaScript。
Then, in your script module, you can initialize as below (I use jQuery for brevity):
然后,在您的脚本模块中,您可以按如下方式进行初始化(为简洁起见,我使用 jQuery):
$("#myLink").click(function(){
var href = $(this).attr("href"),
message = $(this).attr("data-message");
myFunc();
alert(message);
window.location.href = href;
});
This technique leaves your HTML clean and allows you to perform multiple actions on the click event.
这种技术使您的 HTML 保持干净,并允许您对单击事件执行多个操作。
Finally, if you are not familiar with the concept of modules in JavaScript, take a look at Douglas Crockford's book JavaScript, The Good Parts.
最后,如果您不熟悉 JavaScript 中模块的概念,请查看 Douglas Crockford 的书JavaScript,The Good Parts。
回答by Royi Namir
Try this :
试试这个 :
<a href="javascript:void(0)" onclick="alert('myFunc executed');myFunc();window.location='http://google.com'">Click here</a>
<a href="javascript:void(0)" onclick="alert('myFunc executed');myFunc();window.location='http://google.com'">Click here</a>
explanation :
解释 :
javascript:void(0)
Is for u to see a link.
javascript:void(0)
是给你看的链接。