2013-11-28 131 views
0

我想在PHP中創建一個類似於JavaScript的alert()命令的函數,但是OK按鈕的onclick屬性不起作用!爲什麼onclick屬性不起作用?

這裏是我的代碼:

<!DOCTYPE html> 
<?php 
    function alert($title, $text) { 
     $html = '<div id="alert" style="background-color:lightGray; text-align:center; height:500px; width:500px; color: black; position:fixed; top: 50%; left:50%; margin-left:-250px; margin-top:-250px;">'; 
     $html = $html . '<h1 style="background-color:red; border-radius: 15px;">'. $title . '</h1>' . $text; 
     $html = $html . '<br><br><button type="button" style="border-radius:25px; height:50px; width:100px; background-color:white; border:none;" onclick="document.getElementById(\"alert\").style.display=none">OK</button>'; 
     echo $html; 
    } 
    alert('Testing', 'Testing <em>testing</em><b>123</b>'); 
?> 

有什麼不對?我收到一個「警告框」,但確定按鈕不起作用!

+0

如果你calilng這多次,你必須與多個div相同的id,並且只有FIRST發現的id會被'document.getElementById()'返回。 –

+0

這是ID選擇器中的報價不匹配! – adeneo

+0

@MarcB提出了一個有效的觀點。如果您在同一頁面上有兩個警報框,它們都會關閉其中的一個,這很奇怪。每次渲染警告框時生成一個唯一的ID。 – Halcyon

回答

2

element.style.display =「無」,而不是僅僅沒有的

PS只想清楚的JavaScript的概念

+0

'''會與現有的字符串分隔符發生衝突。你必須至少逃脫一次。 – Halcyon

+0

對不起,我很笨,忘了「引用」。 –

+0

謝謝!新問題:http://stackoverflow.com/questions/20272026/how-do-i-get-the-parent-of-an-element –

1

更改爲:

document.getElementById(\"alert\").style.display=\"none\"

我想這也表明,當前的做法是相當可怕的。必須添加所有那些沒有代碼高亮的轉義令人討厭。看看你是否能找到正確的方法;)(提示:你可以)。

相關問題