2014-09-10 102 views
-2

当用户单击指向外部源的链接时,我正在使用以下代码获取免责声明;两个JavaScript警报窗口

$(
    function() { 
    $("a[href^='http://']:not([href*='"+location.hostname+"']), [href^='https://']:not([href*='"+location.hostname+"'])") 
     .attr("target","_blank") 
     .click(function(e) { 
      alert('My message here'); 
     }); 
    }); 

哪些工作,但我需要添加第二个消息,当一个特定的链接点击。我试着添加if和else语句(下面的例子),但这不起作用。我是否使用正确的方法,如果还是应该尝试不同的路线?

$(
function() { 


$(if "a[href^='http://']:not([href*='"+location.hostname+"']), [href^='https://']:not([href*='"+location.hostname+"'])") 
    .attr("target","_blank") 
    .click (function(e) { 
     alert('My original message here'); 
     }); 
    (else if 
    "a[href^='http://theurlhere'") 
    .attr("target","_blank") 
    .click (function(e) { 
     alert('Test'); 
     }); 
    }); 
+3

'(否则if'这是随机的,请看看一些文档 – 2014-09-10 09:00:52

+1

'if'是一个声明,而不是表达 – elclanrs 2014-09-10 09:00:57

回答

3

您不能同时有2个警报。 JavaScript在单线程中执行所有代码,一旦显示警告,脚本执行将不会继续,直到您点击'ok'。

你可以有2个警报的唯一方法是自己实施它们,例如引导程序alertsmodals(或甚至两者)。

您可能还需要完成互动式教学here到已了解jQuery选择

更新:

下面是使用引导和jQuery 2个模式警报的示例代码。它在引导模式中显示2个警报。

的Html

<div id='modal' class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> 
    <div class="modal-dialog modal-sm"> 
    <div class="modal-content"> 
     <div id='alert1' class="alert alert-success" role="alert" style="display:none">Second alert will be shown in 3 seconds</div> 
     <div id='alert2' class="alert alert-info" role="alert" style="display:none">Second alert</div> 
    </div> 
    </div> 
</div> 

<button onclick='showAlerts()'>Show 2 Alerts</button> 

的JavaScript

function showAlerts() { 
    showAlert("alert1"); 
    setTimeout(function() { 
    showAlert('alert2') 
    }, 3000); 
} 

function showAlert(alertId) { 
    $('#' + alertId).show(); 
    $('#modal').modal('show'); 
} 

Here工作plunker。

+0

感谢?。建议和交互式教程链接,我没有想过作为一个选项的模式框,这可能比简单的警报窗口更有效 – hoops78 2014-09-10 09:29:37

+0

@ hoops78您可能想看看原始答案 – 2ooom 2014-09-10 13:21:50

+0

中的示例谢谢。我看了一下,我想我应该能够调整这一点,因为我需要不同的警报,取决于点击哪个链接,而不是警报2后的警报2。 – hoops78 2014-09-10 13:30:41

0

选择器必须分离:

$(function() 
{ 
    $("a[href^='http://']:not([href*='" + location.hostname + "']), href^='https://']:not([href*='" + location.hostname + "'])") 
    .attr("target", "_blank") 
    .click(function(e) 
    { 
     alert('My original message here'); 
    }); 

    $("a[href^='http://theurlhere'") 
    .attr("target", "_blank") 
    .click(function(e) 
    { 
     alert('Test'); 
    }); 
}); 
+0

谢谢。我已经尝试了上述,并且它提出了5次原始警报,而不是新警报。我会做更多的研究并与此相关。 – hoops78 2014-09-10 09:28:07

+0

@ hoops78你可以使用[fiddle](http://jsfiddle.net)提供完整的例子,包括HTML代码。我将能够更新解决问题的答案。 – Regent 2014-09-10 09:30:19

+0

大多数网站是在CMS内,所以我创建了菜单部分[链接](http://jsfiddle.net/04adydj2/) – hoops78 2014-09-10 10:23:05