2014-01-16 38 views
0

我有一个问题后,这是我的代码:的Javascript留在网页上点击一个链接

<a href="Webshop.php" class="Button" onclick="myFunction()">Webshop</a> 

<script> 
    function myFunction() { 
     var r = confirm("If you leave this page your purchase will be gone!"); 
     if (r == true) { 
      window.location = "http://www.titansafes.sgr15.g-o.be/Webshop.php"; 
     } else { 
      return 
     } 
    } 
</script> 

如果您按一下按钮,我得到警告,如果他们点击确定,他们直接回网上商店,如果他们点击取消,他们需要留在页面上。但我怎么能做到最好? 我试过Window.location(不工作),返回不起作用,这对我来说很重要。

+0

尝试'返回false'。 – Vinay

+0

然后阅读此:http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – Vinay

回答

1
<a href="Webshop.php" class="Button" onclick="myFunction();return false;">Webshop</a> 

<script> 
    function myFunction() { 
     var r = confirm("If you leave this page your purchase will be gone!"); 
if (r == true) { 
      window.location = "http://www.titansafes.sgr15.g-o.be/Webshop.php"; 
     } else { 
     } 
    } 
</script> 
+0

谢谢你的答案,事件没有工作,但这样做:D – Bondjens

+0

你可以删除href =“Webshop.php”并添加javascript:void(0);要么 # – Shn

0
<a href="javascript:void(0)" class="Button" onclick="myFunction()">Webshop</a> 
0
`<a href="Webshop.php" class="Button" onclick="myFunction()">Webshop</a> 
<script> 
function myFunction(event) 
{ 
event.preventDefault(); 
var r=confirm("If you leave this page your purchase will be gone!"); 
if (r==true) 
{ 
window.location ="http://www.titansafes.sgr15.g-o.be/Webshop.php"; 
} 

} 
</script>` 
0

这是最好不要使用return false;,但相反在事件处理函数中调用该被传递给它的事件对象参数的方法的preventDefault。事件对象是传递给每个事件处理函数的单个参数。其中两个重要的方法是preventDefault,它可以停止默认的事件动作(在本例中为导航,因为它是一个链接)。第二个重要的方法是stopPropagation,它将停止事件在父元素上被触发 使用return falsehttp://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

那么你的处理器应该是这个样子(添加的preventDefault):

function myFunction(eventObject) { 
    eventObject.preventDefault(); 
    var r=confirm("If you leave this page your purchase will be gone!"); 
    if (r==true) { 
     window.location ="http://www.titansafes.sgr15.g-o.be/Webshop.php"; 
    } 
} 

而且实际上两者都做,这是不是nesecerally你想要什么,知道什么时候使用什么是重要的,作为附注,尽量避免内联事件,如:onclick="CODE"改为使用: element.addEventListener() 方法和它的IE8和更旧的替代品。 http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/

相关问题