Javascript 单击链接时的javascript弹出警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8813674/
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
javascript popup alert on link click
提问by user1022585
I need a javascript 'OK'/'Cancel' alert once I click on a link.
单击链接后,我需要一个 javascript“确定”/“取消”警报。
I have the alert code:
我有警报代码:
<script type="text/javascript">
<!--
var answer = confirm ("Please click on OK to continue.")
if (!answer)
window.location="http://www.continue.com"
// -->
</script>
But how do I make it so this only runs when clicking a certain link?
但是我如何使它只在单击某个链接时运行?
采纳答案by Okan Kocyigit
just make it function,
让它发挥作用,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
回答by muzuiget
You can use the onclick
attribute, just return false
if you don't want continue;
您可以使用该onclick
属性,只是return false
如果您不想继续;
<script type="text/javascript">
function confirm_alert(node) {
return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>
回答by Dmytro Dzyubak
Single line works just fine:
单行工作得很好:
<a href="http://example.com/"
onclick="return confirm('Please click on OK to continue.');">click me</a>
Adding another line with a different link on the same page works fine too:
在同一页面上添加具有不同链接的另一行也可以正常工作:
<a href="http://stackoverflow.com/"
onclick="return confirm('Click on another OK to continue.');">another link</a>
回答by JaredPar
In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML
为此,您需要将处理程序附加到页面上的特定锚点。对于这样的操作,使用像jQuery这样的标准框架要容易得多。例如,如果我有以下 HTML
HTML:
HTML:
<a id="theLink">Click Me</a>
I could use the following jQuery to hookup an event to that specific link.
我可以使用以下 jQuery 将事件连接到该特定链接。
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});