1 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個贊
因此,此代碼的問題在于,它會在循環(huán)的每次迭代中生成一個新的?script
?元素,該元素會覆蓋所有變量和事件偵聽器。
我建議采用不同的方法來做到這一點(diǎn)。
將卡片和模態(tài)降價(jià)留在循環(huán)中
向模態(tài)添加一個唯一的 id,事實(shí)上,您已經(jīng)擁有了
<div id="myModal<?php echo $test['id']; ?>"></div>
現(xiàn)在讓我們?yōu)榘粹o添加一個新屬性,如下所示
<button data-target="#myModal<?php echo $test['id']; ?>"></button>
從循環(huán)中刪除?
script
?標(biāo)記,并為?所有?按鈕編寫一個新的事件偵聽器,該事件偵聽器將僅顯示?id
?屬性等于所單擊按鈕的?data-target
?屬性的模態(tài)
最終結(jié)果如下所示
<?php
? ? include("Config.php");? ? ? ? ? ? ??
? ? $query = ("SELECT * FROM proj");? ? ? ? ? ??
? ? $result = mysqli_query($conn, $query);? ? ? ? ?
? ? while($test = mysqli_fetch_array($result))? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
? ? {? ? ? ? ? ? ? ? ? ? ? ?
? ? ?>? ? ? ? ? ? ? ? ??
? ? <div class="card"><div class="container1">
? ? <div class="card-text">??
? ? <h4><b><?php echo $test['title']; ?></b></h4>
? ? <b>field: </b><?php echo $test['field']; ?></br>? ??
? ? <p><?php echo $test['synopsis']; ?></p>
? <!-- Trigger/Open The Modal -->
? <button data-target="myModal<?php echo $test['id']; ?>" class="action-btn">More Info</button>
? <!-- The Modal -->? ??
? <div id="myModal<?php echo $test['id']; ?>" class="modal">?
? <!-- Modal content -->
? <div class="modal-content">??
? ? <span class="close">×</span>
? ? ? ? <h4><b><?php echo $test['title']; ?></b></h4>
? ? ? ? <p><b>field: </b><?php echo $test['field']; ?></p>? ? ??
? ? ? ? <p><?php echo $test['synopsis']; ?></p>
? ? ? ? <p><?php echo $test['description']; ?></p>? ?
</div>
</div>? ? ??
</div>
</div>
</div>? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? <?php
? ? ? ? ? ? }
? ? ? ? ? ? mysqli_close($conn);
? ? ? ? ? ? ?>
? ? ? ? ? ?<script>
var buttons = document.querySelectorAll(".action-btn");
// Feel free to use any other way to iterate over buttons
for (var i = 0; i < buttons.length; i++) {
? buttons[i].addEventListener("click", function (event) {
? ? var modal = (document.getElementById(
? ? ? event.target.getAttribute("data-target")
? ? ).style.display = "block");
? });
}
// Add code to close modals
</script>? ?
注意:Bootstrap 提供了一種更簡單的方式來使用模態(tài)框并提供所有這些功能。
- 1 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報(bào)