我想添加一個點擊事件到一個動態變化的ID按鈕元素。然而,要真正讓彈出窗口出現,我必須點擊兩次按鈕......我知道這是這樣發生的,因爲我在做點擊事件時出錯。但我無法弄清楚如何解決這個問題。 你可以嗎?我出去拉我的頭髮在這個...JavaScript的onClick:我必須點擊兩次出現模式
感謝這麼多提前
// Get the modal
function getPopup(venue_id){
\t var modal = document.getElementById('myModal');
\t var btn = document.getElementById("myBtn"+venue_id);
\t var venue = document.getElementById("title"+venue_id).innerHTML;
\t document.getElementById("eventTitle").innerHTML = "<h3>"+venue+"</h3>";
\t var span = document.getElementsByClassName("close")[0];
\t btn.onclick = function() {
\t \t modal.style.display = "block";
\t }
\t span.onclick = function() {
\t \t modal.style.display = "none";
\t }
\t window.onclick = function(event) {
\t \t if (event.target == modal) {
\t \t \t modal.style.display = "none";
\t \t }
\t }
}
function sentPopup(){
\t document.getElementById('myModal').style.display ="none";
\t var modal = document.getElementById('thanksMessage');
\t var span = document.getElementById("close");
\t modal.style.display = "block";
\t span.onclick = function() {
\t \t modal.style.display = "none";
\t }
\t window.onclick = function(event) {
\t \t if (event.target == modal) {
\t \t \t modal.style.display = "none";
\t \t }
\t }
}
<?php /* $venue_id is being populated by a php function which doesnt matter for this click issue to solve */
<button class="btn" id="myBtn'.$venue_id.'" onclick="getPopup('.$venue_id.')">Unverbindlich anfragen</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">x</span>
<p class="venuePopupTitle" id="eventTitle"></p>
<form>my form</form>
</div>
</div>
?>
從getPopup()中刪除window.onclick並檢查! 這個window.onclick第一次讓模態顯示爲空。因此你需要再次點擊按鈕。 – Pat
請發佈一個最小化,完整和可驗證的示例http://stackoverflow.com/help/mcve – yuriy636
您的模式中的按鈕?你可以發佈你的html代碼片段嗎? – klikas