0

Нужно реализовать модальное окно для каждого товара с его описанием. На данный момент у меня есть одно общее модальное окно с Id

// Get the modal
    var modal = document.getElementById('myModal');

// Get the button that opens the modal
    var btn = document.querySelectorAll(".myBtn");

// Get the <span> element that closes the modal
    var close = document.querySelector("button.close");

// When the user clicks on <span> (x), close the modal
    close.onclick = function() {
        modal.style.display = "none";
    }

// When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };
};
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
                    <button class="myBtn" onclick="getElementById('myModal').style.display = 'block'">Open Modal</button>

                    <!-- The Modal -->
                    <div id="myModal" class="modal">

                        <!-- Modal content -->
                        <div class="modal-content">
                            <button class="close">&times;</button>
                            <p><?php echo $details ?></p>
                        </div>

                    </div>

В данном случае выводится только первое описание товара. Если делаю не в модалке - значения выводятся для каждого свое. Сделал вывод что нужно модальное окно сделать классами и выбирать через querySelectorAll все формы. Затем каждую форму выводить в своей карточке товаров через this.

При переделывании скрипта получилось следущее:

// Get the modal
    var modal = document.querySelectorAll('.myModal');

// Get the button that opens the modal
    var btn = document.querySelectorAll(".myBtn");

// Get the <span> element that closes the modal
    var close = document.querySelector("button.close");

// When the user clicks on the button, open the modal
//     btn.onclick = function() {
//         modal.style.display = "block";
//     }

// When the user clicks on <span> (x), close the modal
    close.onclick = function() {
        modal.style.display = "none";
    }

// When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };
};
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
 <button class="myBtn" onclick="document.querySelectorAll('myModal').style.display = 'block'">Open Modal</button>

                    <!-- The Modal -->
                    <div class="myModal modal">

                        <!-- Modal content -->
                        <div class="modal-content">
                            <button class="close">&times;</button>
                            <p><?php echo $details ?></p>
                        </div>

                    </div>

В итоге скрипт перестал запускаться, прошу помощи в реализации

2 ответа 2

0

При беглом осмотре выявил как минимум следующие замечания

  1. В последней строке javascript-кода лишняя скобка };
  2. В переменной modal находится коллекция элементов, а вы работаете с ним как с одним элементом modal.style.display = "none";
3
  • 1. Эта скобка от window.onload - извиняюсь 2. Проблема вероятнее всего в этой строчке <button class="myBtn" onclick="document.querySelectorAll('myModal').style.display = 'block'">Open Modal</button> Но не знаю как правильно написать чтобы применялось именно к данному div .myModal 25 дек 2017 в 13:31
  • c Id такое можно сделать а вот с классом - проблематично 25 дек 2017 в 13:31
  • Используйте вместо document.querySelectorAll метод document.querySelector (без All)
    – vihtor
    25 дек 2017 в 13:57
0

Вышел из проблемы следующим костылем

<button class="myBtn prise_bat" data-sku='' onclick="getElementById('myModal__<?=$i;?>').style.display = 'block'">Подробнее</button>

Некрасиво написано, но заработало.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.