2017-08-15 19 views
1

我試圖通過下面的PHP回聲使用javacript confirm()框,它不工作。Onclick confirm()在PHP回顯時不工作

echo '<a href="http://sdfsdfs.com?keepThis=true&TB_iframe=true&height=10&width=1200&x=2342342&enter_other_room=2" class="box" TARGET="_self" oncontextmenu="return false;" onclick="confirm(\"Are you sure you want to enter the users\'s Room?\");\">User\'s Room</a>'; 

我在這裏錯過了什麼?

+1

我想你 「逃離」 太多了' 「'....嘗試改變'房\?」); 「?' - >'房\」 \)「' –

+0

檢查元素通過控制檯,你會看到,如果你有一個錯字(這可能是這種情況) – Bdloul

+0

也可以考慮(如果可能),而不是'回聲「你的HTML在這裏」'只是'?>你的HTML在這裏< ?php' - 這樣你就不需要做* quote escape * shuffle儘可能多 –

回答

2

您無法在HTML屬性內跳過引號,因此onclick="confirm(\"...\");"將不起作用。在字符串周圍放置單引號。由於它位於PHP單引號字符串中,因此您需要將它們轉義爲PHP。

而且由於字符串中包含一個撇號,所以您需要將其轉義爲Javascript。您必須加倍反斜槓才能在PHP字符串中獲得文字反斜槓。還有第三個反斜槓爲了逃避PHP。

echo '<a href="http://sdfsdfs.com?keepThis=true&TB_iframe=true&height=10&width=1200&x=2342342&enter_other_room=2" class="box" TARGET="_self" oncontextmenu="return false;" onclick="confirm(\'Are you sure you want to enter the users\\\'s Room?\');\">User\'s Room</a>'; 
+0

這會產生一個php錯誤。 – gtilflm

+0

對不起,在撇號之前需要第三個反斜槓。 – Barmar

1

js CONFIRM()函數返回true或false。你不檢查用戶的答案。

這是一個通用函數,它會詢問您的問題並將用戶發送到您的URL。把它放在你的HTML中。

<script> 
function myChoice(question,location) { 
    var answer = confirm(question); 
    if (answer) { 
     window.location.href=location; 
    } 
    else { 
     alert("you're staying here!"); 
    } 
} 
</script> 

您仍然可以使用PHP echo()生成問題和URL,重用相同的函數。

echo ' 
<a href="#" class="box" TARGET="_self" oncontextmenu="return false;" 
onclick="myChoice(\'Are you sure you want to enter the users Room?\',\'http://sdfsdfs.com?keepThis=true&TB_iframe=true&height=10&width=1200&x=2342342&enter_other_room=2\');">Users Room</a>';