【问题标题】:javascript popup alert on link click单击链接时的javascript弹出警报
【发布时间】:2012-01-11 03:06:31
【问题描述】:

单击链接后,我需要一个 javascript 'OK'/'Cancel' 警报。

我有警报代码:

<script type="text/javascript">
<!--
var answer = confirm ("Please click on OK to continue.")
if (!answer)
window.location="http://www.continue.com"
// -->
</script>

但是我该如何让它只在点击某个链接时才运行呢?

【问题讨论】:

    标签: javascript hyperlink alert confirm confirmation


    【解决方案1】:

    您可以使用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>
    

    【讨论】:

    • 这实际上效果更好 - 应该接受更通用的解决方案。
    【解决方案2】:

    单行就可以了:

    <a href="http://example.com/"
     onclick="return confirm('Please click on OK to continue.');">click me</a>
    

    在同一页面上添加具有不同链接的另一行也可以:

    <a href="http://stackoverflow.com/"
     onclick="return confirm('Click on another OK to continue.');">another link</a>
    

    【讨论】:

      【解决方案3】:

      让它发挥作用,

      <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>
      

      【讨论】:

      • @user1022585 你需要return false 来阻止链接离开。请参阅下面的答案 - Confirm 方法返回一个 boolean,您可以使用它退出您的函数...
      • 对不起,我复制了你的代码,你的代码是错误的。如果用户说“ok”的答案将设置为“true”,那么我们不需要“!”,我改变了它。
      • 通过javascript打开空白弹出窗口:jswin = window.open("", "test-window", "width=350,height=150");
      • 我的 html 中有多个 href 标签,我想为每个单独的链接执行不同的警报弹出窗口,那么我怎么知道 javascript 是从哪个链接访问的??
      • @NischayaSharma,查看@muzuiget 的answer。你不能在href中传递this。您应该使用onclick,并传递参数this
      【解决方案4】:

      为此,您需要将处理程序附加到页面上的特定锚点。对于这样的操作,使用像jQuery 这样的标准框架要容易得多。例如,如果我有以下 HTML

      HTML:

      <a id="theLink">Click Me</a>
      

      我可以使用以下 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"
          }
        });
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多