简体   繁体   English

使用window.onclick隐藏div —很复杂

[英]hide divs with window.onclick — it's complicated

PLEASE NOTE: this is a javascript question even though the code here is in PHP. 请注意:这是一个JavaScript问题,即使此处的代码是PHP。 WARNING: long explanation coming up :-) 警告:详细解释即将出现:-)

I have a PHP while loop which returns a variable number of rows from a MYSQL set. 我有一个PHP while循环,该循环从MYSQL集返回可变数量的行。 Included in each row of SQL data, there is a url for a googlemaps iframe, which is dynamically assigned to a modal popup window. SQL数据的每一行中都包含googlemaps iframe的网址,该网址已动态分配给模式弹出窗口。 The problem comes from the fact that I have to generate the javascript code to open and close each modal popup dynamically; 问题出在我必须生成javascript代码以动态地打开和关闭每个模式弹出窗口的事实。 so there is a substantial amount of javascript in the form of PHP echo (something I hate to do, but in this case, it seemed like the best option). 因此,有大量的JavaScript以PHP echo的形式出现(我讨厌这样做,但是在这种情况下,这似乎是最好的选择)。 Here is the code I have: 这是我的代码:

$sql .= " WHERE " . implode(" AND ", $where_clause); 
            $result = $conn->query($sql);
            $loopcount = 1; //enumerate each returned MYSQL row for popup variables

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                echo '<!--ENTRY:' . $loopcount . '-->';

            //START POPUP CODE FOR GOOGLEMAPS
                echo '<H1><span id="open_popup_' . $loopcount . '">' . $row["address"] . ',&nbsp;' . $row["city"] . '</span></H1>' . 

                '<div id="myModal_' . $loopcount . '" class="modal">' .
                    '<div class="modal-content"><iframe src="' . $row["map"] . '" width="600" height="450"></iframe></div>' . 
                    '</div>'; 

                echo '<script>
                    var modal_' . $loopcount . ' = document.getElementById(\'myModal_' . $loopcount . '\');
                    var popup_id_' . $loopcount . ' = document.getElementById("open_popup_' . $loopcount . '");

            // Open modal--THIS PART WORKS FINE
                popup_id_' . $loopcount . '.onclick = function() {
                    modal_' . $loopcount . '.style.display = "block";
                    }

            // Close modal onclick outside the modal--THIS PART DOES NOT WORK
                window.onclick = function(event) {
                    if (event.target == modal_' . $loopcount . ') {
                        modal_' . $loopcount . '.style.display = "none";
                        }
                    }
                </script>';

                $loopcount++; //INCREMENT LOOPCOUNT FOR EACH RETURNED ROW

                }
            } else {
                echo "0 results";
                }
        $conn->close();
    ?>  

So as I mentioned in the comment, the open modal window part works perfectly because it can easily target the correct dive by id (eg 'modal_1', 'modal_2' etc.). 因此,正如我在评论中提到的那样,打开的模式窗口部分可以完美地工作,因为它可以轻松地按ID定位正确的潜水(例如“ modal_1”,“ modal_2”等)。 However, when I click outside the window, only the LAST instance closes; 但是,当我在窗口外单击时,仅LAST实例关闭; any others that are there remain open and I have to reload the page to close them. 任何其他仍保持打开状态,我必须重新加载页面以将其关闭。 I know that this is because the event.target will get reset with each PHP loop, and by the time the page is generated, it will only apply to the last instance. 我知道这是因为event.target将在每个PHP循环中重置,并且到生成页面时,它仅适用于最后一个实例。

My first thought was to put a function outside of the PHP loop which hides all divs of class modal , but then that would be triggered each time the user clicked anywhere on the page, and therefore, would also hide the div when the user clicks on the link to open it. 我的第一个想法是在PHP循环之外放置一个函数,该函数可隐藏modal类的所有div,但是每次用户单击页面上的任何位置时都会触发该函数,因此,当用户单击div时也将隐藏div打开它的链接。 So as far as I can tell, I have to keep this function inside my PHP loop too. 据我所知,我也必须将此function保留在PHP循环中。

As such, I need to somehow tailor the javascript so that each generated function(event) will only be triggered if the associated div (by ID... 'modal_n') is shown. 因此,我需要以某种方式定制javascript,以便仅在显示关联的div(通过ID ...“ modal_n”)时触发每个生成的function(event) Beyond that, I suppose that it could simply hide all divs of class 'modal' rather than targeting the specific div which is visible (although I would prefer a method which targeted only that specific div). 除此之外,我想它可以简单地隐藏“模式”类的所有div,而不是针对可见的特定div(尽管我更喜欢只针对特定div的方法)。

I have tried my best to explain the problem clearly. 我已尽力清楚地解释了这个问题。 As always, I would be very grateful for any help from the experts! 一如既往,我将非常感谢专家的任何帮助!

Check the count of open modal windows in this function: 在此功能中检查打开的模式窗口的数量:

// Close modal onclick outside the modal
window.onclick = function(event) {
    if(event.target.className != "open_Modal"){
        var arr = document.getElementsByClassName("modal")
        var modal_count = 0; //Initialize Count
        for(var i = 0; i < arr.length; i++){
           if(arr[i].style.display == "block"){
              modal_count++; //Increase count for all modals with display: block
           }
        }
       if (modal_count > 0) //Run function only if modal_count is more than 0
       { 
         for(var i = 0; i < arr.length; i++){
           arr[i].style.display = "none"; 
           modal_count = 0; //Reset modal_count to 0 again
         }
       }
    }   
}

This way your function will not run unless there is a minimum of 1 modal window open on your page. 这样,除非您的页面上至少打开了一个模态窗口,否则您的函数将无法运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM