首页 > 解决方案 > 我通过 PHP 定义的 Bootstrap 5 模态和其他东西不起作用

问题描述

对于我的一生,我无法理解为什么在以下示例中调用模态时遇到问题:

<?php
$sql = "SELECT
            master_traits_index,
            trait_name AS name
        FROM
            `cp_2020_master_traits`
        WHERE
            trait_type = 1;";
$query_result = $mysqli->query($sql);
$attributes = [];

while($gotinfo2=mysqli_fetch_assoc($query_result)){
    $attributes[] = $gotinfo2; //assign whole values to array
}

// Attribute Modals 

foreach ($attributes as $row2){
    echo('<div class="modal fade" id="'.$row2['master_traits_index'].'_staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="'.$row2['master_traits_index'].'Label" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="'.$row2['master_traits_index'].'Label">'.$row2['name'].'</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Understood</button>
          </div>
        </div>
      </div>
    </div>');
}

foreach ($attributes as $row1) {
    echo('<div class="col">
            <button type="button" class="btn btn-sm btn-outline-dark position-relative" data-bs-toggle="modal" href="#'.$row1['master_traits_index'].'_staticBackdrop">
            <h4>'.$row1['name'].'</h4>
            <p>[ <em id="'.$row1['master_traits_index'].'_final">1</em> ]</p>
            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-dark" id="'.$row1['master_traits_index'].'_cps_spent">0.5 cp</span>
            </button>
        </div>');
}
?>

当我检查页面输出时,所有 id 都根据按钮匹配,所以它应该调用模态,但它没有。当您有大量类似的数据要处理时,您应该能够使用 PHP 来构建这种东西,对吧?

底线是,当我单击与使用 php 循环中的变量创建的模式相对应的按钮时,没有任何反应。当我在浏览器中检查它时。我不知道为什么它没有响应。

标签: phphtmlbootstrap5-modal

解决方案


id您面临的问题是由于 HTML值不能以数字开头的事实引起的:

在此处输入图像描述

在这里阅读更多:https ://www.w3schools.com/html/html_id.asp

解决方案:重构您的 HTML 并在数值前添加一些前缀。这将修复您的 HTMLid属性。从那时起,如果您有一些代码假定了这些 HTMLid的值,那么您也需要对其进行重构。


推荐阅读