本文介绍了带有子菜单的 PHP Bootstrap 4 导航菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原帖

我想用 Bootstrap 4 在 PHP 中创建一个导航菜单.问题是 <li> 的一个不正确(来自 dropdown,它不会变成下拉菜单,而只是一个普通的 nav-item).如果您想使用 <ul> 制作普通菜单,则此代码可以正常工作,但是使用引导程序,您需要有一个 nav-item名为 Dropdown 的 id 2

  • 上的 dropdown.我该怎么做?

    我希望这是足够的信息.

    这是数组():

    数组(大小=3)0 =>数组(大小=5)0 =>数组(大小=3)'id' =>字符串1"(长度=1)'menu_naam' =>字符串家"(长度=4)'parent_id' =>字符串'0'(长度=1)1 =>数组(大小=3)'id' =>字符串2"(长度=1)'menu_naam' =>字符串下拉列表"(长度=4)'parent_id' =>字符串'0'(长度=1)2 =>数组(大小=3)'id' =>字符串3"(长度=1)'menu_naam' =>字符串 'Winkelwagen'(长度 = 11)'parent_id' =>字符串'0'(长度=1)3 =>数组(大小=3)'id' =>字符串4"(长度=1)'menu_naam' =>字符串联系人"(长度=7)'parent_id' =>字符串'0'(长度=1)4 =>数组(大小=3)'id' =>字符串5"(长度=1)'menu_naam' =>字符串'反馈'(长度=8)'parent_id' =>字符串'0'(长度=1)2 =>数组(大小=1)0 =>数组(大小=3)'id' =>字符串'6'(长度=1)'menu_naam' =>字符串子菜单"(长度=8)'parent_id' =>字符串2"(长度=1)6 =>数组(大小=1)0 =>数组(大小=3)'id' =>字符串7"(长度=1)'menu_naam' =>字符串子子菜单"(长度=12)'parent_id' =>字符串'6'(长度=1)

    这是我用来构建菜单的 PHP:

    execute()) {while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {$array[$row['parent_id']][] = $row;}loop_array($array);}}函数 loop_array($array = array(), $parent_id = 0) {if (!empty($array[$parent_id])) {echo "<ul class="navbar-nav mr-auto">";foreach ($array[$parent_id] 作为 $item) {echo "
  • ";echo "<a href="#" class="nav-link">".$item['menu_naam'] ."</a>";loop_array2($array, $item['id']);echo "</li>";}echo "</ul>";}}function loop_array2($array = array(), $parent_id = 0) {if (!empty($array[$parent_id])) {echo "<li class="nav-item dropdown">";foreach ($array[$parent_id] 作为 $item) {echo "<a href="#" class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">".$item['menu_naam'] ."</a>";loop_array3($array, $item['id']);}echo "</li>";}}function loop_array3($array = array(), $parent_id = 0) {if (!empty($array[$parent_id])) {echo "<div class="dropdown-menu" aria-labelledby="navbarDropdown">";foreach ($array[$parent_id] 作为 $item) {echo "<a class="dropdown-item" href="#">".$item['menu_naam'] ."</a>";}回声</div>";}}
  • 我真的希望有人能帮我解决这个问题,我应该向数据库添加一些东西,以便它知道这是一个下拉列表吗?我认为我的代码太大而且太复杂,应该有一个更简单的方法,但我不知道如何.我想我需要一种完全不同的方法.如果你能在正确的方向上帮助我,那就太好了.

    还要感谢制作子菜单教程的人(在这里您还可以看到菜单是如何使用

    • 构建的并完成它需要做的事情,但不适用于 bootstrap):https://www.youtube.com/watch?v=Ol63V4R-TdI

      我在这里找到了一种解决方案:Dynamic menu php bootstrap mysql

      我现在拥有的是:

      function drawMenu($pdo, $parent_id, $level = null) {$sql = $pdo->prepare("SELECT * FROM menus where parent_id = $parent_id");$sql->execute();foreach ($sql->fetchAll() 作为 $row) {$sql = $pdo->prepare("SELECT count(*) FROM menus where parent_id = " . $row['id'] . "");$sql->execute();//该项目是父项,所以再次递归//var_dump($sql->fetchAll()[0][0]);if($sql->fetchAll()[0][0] !=='0' && $level !== 0){echo "<li class="nav-item dropdown"><a href="" . $row['url'] . "" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">".$row['menu_naam'] ."</a><div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
      ";drawMenu($pdo, $row[0], $level - 1);echo "</div></li>
      ";}else {//项目是叶子或者我们到达了最终级别,即基本情况,所以打印项目标签echo "<li class="nav-item"><a href="#" class="nav-link">".$row['menu_naam'] ."</a></li>
      ";}}}?><header class="navbar navbar-dark bg-dark fixed-top navbar-expand-sm"><a class="navbar-brand" href="#">网上商店</a><button class="navbar-toggler" style="background: #000000" type="button" data-toggle="collapse" data-target="#navbar-header" aria-controls="navbar-header">&#9776;<div class="navbar-collapse 折叠显示" id="navbar-header"><ul class="navbar-nav mr-auto"><?phpdrawMenu($pdo, 0, null);?>
  • </标题>

    但现在的问题是它打印了多个

    HTML 现在看起来像这样:

    <ul class="navbar-nav mr-auto"><li class="nav-item"><a href="#" class="nav-link"><span class="fas fa-home"></span>主页</a></li><li class="nav-item dropdown"><a href="#" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true"aria-expanded="false">Dropdown</a><div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"><li class="nav-item dropdown"><a href="#" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true"aria-expanded="false">子菜单</a><div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"><li class="nav-item"><a href="#" class="nav-link">Sub-sub Menu</a></li></div></li></div></li><li class="nav-item"><a href="#" class="nav-link"><span class="fas fa-shopping-cart"></span>温克尔瓦根</a></li><li class="nav-item"><a href="#" class="nav-link">联系方式</a></li><li class="nav-item"><a href="#" class="nav-link">反馈</a></li>

    解决方案

    我对 bootstrap 4.1 进行了一些更改

    .navbar .dropdown-toggle, .navbar .dropdown-menu a {光标:指针;}.navbar .dropdown-item.active, .navbar .dropdown-item:active {颜色:继承;文字装饰:无;背景色:继承;}.navbar .dropdown-item:focus, .navbar .dropdown-item:hover {颜色:#16181b;文字装饰:无;背景颜色:#f8f9fa;}@media(最小宽度:767px){.navbar .dropdown-toggle:not(.nav-link)::after {显示:内联块;宽度:0;高度:0;左边距:.5em;垂直对齐:0;边框底部:.3em 实心透明;边框顶部:.3em 实心透明;左边框:.3em 实心;}}</风格><script type="text/javascript">$(document).ready(function () {$('.navbar .dropdown-item').on('click', function (e) {var $el = $(this).children('.dropdown-toggle');var $parent = $el.offsetParent(".dropdown-menu");$(this).parent("li").toggleClass('open');if (!$parent.parent().hasClass('navbar-nav')) {如果 ($parent.hasClass('show')) {$parent.removeClass('show');$el.next().removeClass('show');$el.next().css({"top": -999, "left": -999});} 别的 {$parent.parent().find('.show').removeClass('show');$parent.addClass('show');$el.next().addClass('show');$el.next().css({"top": $el[0].offsetTop, "left": $parent.outerWidth() - 4});}e.preventDefault();e.stopPropagation();}});$('.navbar .dropdown').on('hidden.bs.dropdown', function () {$(this).find('li.dropdown').removeClass('show open');$(this).find('ul.dropdown-menu').removeClass('show open');});});<?php 函数 menu_builder1($db, $parent_id) {$sql = $db->prepare("SELECT * FROM menu WHERE status = 1 ORDER BY position ASC");if($sql->execute()) {while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {$array[$row['menu_sub_id']][] = $row;}main_menu1($array);}}函数 main_menu1($array, $parent_id = false) {if(!empty($array[$parent_id])) {foreach ($array[$parent_id] 作为 $item) {if ($item['dropdown'] == false) {echo '<li class="nav-item active"><a class="nav-link" href="' . $item['href'] . '">'.$item['name'] .'</a></li>';}elseif ($item['dropdown'] == true) {echo '<li class="nav-item dropdown"><a class="nav-link dropdown-toggle" id="dropdown2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="假">'.$item['name'] .'</a>';sub_menu1($array, $item['menu_id']);echo '</li>';}}}}function sub_menu1($array = array(), $parent_id = false) {if(!empty($array[$parent_id])) {echo '
      ';foreach ($array[$parent_id] 作为 $item) {if ($item['dropdown'] == false) {echo '<li class="dropdown-item"><a href="' . $item['href'] . '">'.$item['name'] .'</a></li>';}elseif ($item['dropdown'] == true) {echo '<li class="dropdown-item dropdown"><a class="dropdown-toggle" id="dropdown2-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded=假">'.$item['name'] .'</a>';sub_sub_menu1($array, $item['menu_id']);echo '</li>';}}echo "</ul>";}}function sub_sub_menu1($array = array(), $parent_id = false) {if(!empty($array[$parent_id])) {echo '
        ';foreach ($array[$parent_id] 作为 $item) {if ($item['dropdown'] == false) {echo '<li class="dropdown-item"><a href="' . $item['href'] . '">'.$item['name'] .'</a></li>';}}echo "</ul>";}}?><div class="navbar navbar-expand-md navbar-dark bg-dark mb-4" role="navigation"><button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle导航"><span class="navbar-toggler-icon"></span><div class="collapse navbar-collapse" id="navbarCollapse"><ul class="navbar-nav mr-auto"><?=menu_builder1($db, 0)?>

    还有一些 SQL 信息

    创建表`菜单`(`menu_id` int(11) 非空,`menu_sub_id` int(11) 非空,`已添加`时间戳非空 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`status` int(1) NOT NULL DEFAULT '1',`href` varchar(150) 非空,`class` varchar(150) 非空,`position` int(3) 非空,`name` varchar(150) 非空,`description` varchar(500) 非空,`dropdown` int(11) 非空,`sub_menu` int(1) 非空,`sub_sub_menu` int(1) 非空) 引擎=InnoDB 默认字符集=utf8;更改表`菜单`添加主键 (`menu_id`);更改表`菜单`修改`menu_id` int(11) NOT NULL AUTO_INCREMENT;犯罪;

    ORIGINAL POST

    I want to create a navigation menu in PHP with Bootstrap 4. Problem is that one of the <li>'s is not right (the one from dropdown, it doesn't become a dropdown but just a normal nav-item). This code works alright if you want to make a normal menu with <ul> and <li> but with bootstrap you need to have a nav-item dropdown on the <li> of id 2 named Dropdown. How would I do this?

    I hope this is enough information.

    This is the array():

    array (size=3)
      0 =>
        array (size=5)
          0 =>
            array (size=3)
              'id' => string '1' (length=1)
              'menu_naam' => string 'Home' (length=4)
              'parent_id' => string '0' (length=1)
          1 =>
            array (size=3)
              'id' => string '2' (length=1)
              'menu_naam' => string 'Dropdown' (length=4)
              'parent_id' => string '0' (length=1)
          2 =>
            array (size=3)
              'id' => string '3' (length=1)
              'menu_naam' => string 'Winkelwagen' (length=11)
              'parent_id' => string '0' (length=1)
          3 =>
            array (size=3)
              'id' => string '4' (length=1)
              'menu_naam' => string 'Contact' (length=7)
              'parent_id' => string '0' (length=1)
          4 =>
            array (size=3)
              'id' => string '5' (length=1)
              'menu_naam' => string 'Feedback' (length=8)
              'parent_id' => string '0' (length=1)
      2 =>
        array (size=1)
          0 =>
            array (size=3)
              'id' => string '6' (length=1)
              'menu_naam' => string 'Sub Menu' (length=8)
              'parent_id' => string '2' (length=1)
      6 =>
        array (size=1)
          0 =>
            array (size=3)
              'id' => string '7' (length=1)
              'menu_naam' => string 'Sub Sub Menu' (length=12)
              'parent_id' => string '6' (length=1)
    

    This is the PHP I use to build the menu:

    <?php
    function menu_builder() {
    global $pdo;
    
       $sql = $pdo->prepare("SELECT * FROM menus");
    
       if ($sql->execute()) {
            while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
                 $array[$row['parent_id']][] = $row;
            }
            loop_array($array);
        }
    }
    function loop_array($array = array(), $parent_id = 0) {
        if (!empty($array[$parent_id])) {
            echo "<ul class="navbar-nav mr-auto">";
            foreach ($array[$parent_id] as $item) {
                echo "<li class="nav-item">";
                echo "<a href="#" class="nav-link">" . $item['menu_naam'] . "</a>";
                loop_array2($array, $item['id']);
                echo "</li>";
            }
            echo "</ul>";
        }
    }
    function loop_array2($array = array(), $parent_id = 0) {
        if (!empty($array[$parent_id])) {
            echo "<li class="nav-item dropdown">";
            foreach ($array[$parent_id] as $item) {
                echo "<a href="#" class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">" . $item['menu_naam'] . "</a>";
                loop_array3($array, $item['id']);
            }
            echo "</li>";
        }
    }
    function loop_array3($array = array(), $parent_id = 0) {
        if (!empty($array[$parent_id])) {
            echo "<div class="dropdown-menu" aria-labelledby="navbarDropdown">";
            foreach ($array[$parent_id] as $item) {
                echo "<a class="dropdown-item" href="#">" . $item['menu_naam'] . "</a>";
            }
            echo "</div>";
        }
    }
    

    I really hope someone can help me with this, should I add something to the database so it will know it's a dropdown? I think my code is too big and to complicated, there should be a easyer way but I don't know how. I think I need a whole other approach. If you could only help me in the right direction it would be fine too.

    Also some credit to the guy who made the sub menu tutorial (here you can also see how the menu is build with <ul> and <li> and does exactly what it needs to do, but not for bootstrap): https://www.youtube.com/watch?v=Ol63V4R-TdI

    EDIT:I found a kind of a solution over here: Dynamic menu php bootstrap mysql

    What I have now is:

    function drawMenu($pdo, $parent_id, $level = null) {
        $sql = $pdo->prepare("SELECT * FROM menus where parent_id = $parent_id");
        $sql->execute();
    
        foreach ($sql->fetchAll() as $row) {
            $sql = $pdo->prepare("SELECT count(*) FROM menus where parent_id = " . $row['id'] . "");
            $sql->execute();
            // The item is parent, so do recursion again
            //var_dump($sql->fetchAll()[0][0]);
            if($sql->fetchAll()[0][0] !== '0' && $level !== 0){
                echo "<li class="nav-item dropdown"><a href="" . $row['url'] . "" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">" . $row['menu_naam'] . "</a><div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
    ";
                drawMenu($pdo, $row[0], $level - 1);
                echo "</div></li>
    ";
            }
            else { // The item is a leaf or we reach the end level, i.e. base case, so do print the item label
                echo "<li class="nav-item"><a href="#" class="nav-link">" . $row['menu_naam'] . "</a></li>
    ";
            }
        }
    }
    ?>
    <header class="navbar navbar-dark bg-dark fixed-top navbar-expand-sm">
        <a class="navbar-brand" href="#">Webshop</a>
        <button class="navbar-toggler" style="background: #000000" type="button" data-toggle="collapse" data-target="#navbar-header" aria-controls="navbar-header">
            &#9776;
        </button>
        <div class="navbar-collapse collapse show" id="navbar-header">
            <ul class="navbar-nav mr-auto">
            <?php
            drawMenu($pdo, 0, null);
            ?>
            </ul>
        </div>
    </header>
    

    But the problem now is that it prints multiple

    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
    

    The HTML looks like this now:

    <div class="navbar-collapse collapse show" id="navbar-header">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item"><a href="#" class="nav-link"><span class="fas fa-home"></span> Home</a></li>
            <li class="nav-item dropdown"><a href="#" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a><div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <li class="nav-item dropdown"><a href="#" class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Sub Menu</a><div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <li class="nav-item"><a href="#" class="nav-link">Sub-sub Menu</a></li>
            </div></li>
            </div></li>
            <li class="nav-item"><a href="#" class="nav-link"><span class="fas fa-shopping-cart"> </span> Winkelwagen</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Contact</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Feedback</a></li>
        </ul>
    </div>
    
    解决方案

    I have maked some changes for bootstrap 4.1

    <style type="text/css">
        .navbar .dropdown-toggle, .navbar .dropdown-menu a {
            cursor: pointer;
        }
    
        .navbar .dropdown-item.active, .navbar .dropdown-item:active {
            color: inherit;
            text-decoration: none;
            background-color: inherit;
        }
    
        .navbar .dropdown-item:focus, .navbar .dropdown-item:hover {
            color: #16181b;
            text-decoration: none;
            background-color: #f8f9fa;
        }
    
        @media (min-width: 767px) {
            .navbar .dropdown-toggle:not(.nav-link)::after {
                display: inline-block;
                width: 0;
                height: 0;
                margin-left: .5em;
                vertical-align: 0;
                border-bottom: .3em solid transparent;
                border-top: .3em solid transparent;
                border-left: .3em solid;
            }
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.navbar .dropdown-item').on('click', function (e) {
                var $el = $(this).children('.dropdown-toggle');
                var $parent = $el.offsetParent(".dropdown-menu");
                $(this).parent("li").toggleClass('open');
    
                if (!$parent.parent().hasClass('navbar-nav')) {
                    if ($parent.hasClass('show')) {
                        $parent.removeClass('show');
                        $el.next().removeClass('show');
                        $el.next().css({"top": -999, "left": -999});
                    } else {
                        $parent.parent().find('.show').removeClass('show');
                        $parent.addClass('show');
                        $el.next().addClass('show');
                        $el.next().css({"top": $el[0].offsetTop, "left": $parent.outerWidth() - 4});
                    }
                    e.preventDefault();
                    e.stopPropagation();
                }
            });
    
            $('.navbar .dropdown').on('hidden.bs.dropdown', function () {
                $(this).find('li.dropdown').removeClass('show open');
                $(this).find('ul.dropdown-menu').removeClass('show open');
            });
    
        });
    </script>
    
    <?php function menu_builder1($db, $parent_id) {
        $sql = $db->prepare("SELECT * FROM menu WHERE status = 1 ORDER BY position ASC");
        if($sql->execute()) {
            while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
                $array[$row['menu_sub_id']][] = $row;
            }
            main_menu1($array);
        }
    }
    function main_menu1($array, $parent_id = false) {
        if(!empty($array[$parent_id])) {
            foreach ($array[$parent_id] as $item) {
                if ($item['dropdown'] == false) {
                    echo '<li class="nav-item active"><a class="nav-link" href="' . $item['href'] . '">' . $item['name'] . '</a></li>';
                }
                elseif ($item['dropdown'] == true) {
                    echo '<li class="nav-item dropdown"><a class="nav-link dropdown-toggle" id="dropdown2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . $item['name'] . '</a>';
                    sub_menu1($array, $item['menu_id']);
                    echo '</li>';
                }
            }
        }
    }
    function sub_menu1($array = array(), $parent_id = false) {
        if(!empty($array[$parent_id])) {
            echo '<ul class="dropdown-menu" aria-labelledby="dropdown2">';
            foreach ($array[$parent_id] as $item) {
                if ($item['dropdown'] == false) {
                    echo '<li class="dropdown-item"><a href="' . $item['href'] . '">' . $item['name'] . '</a></li>';
                }
                elseif ($item['dropdown'] == true) {
                    echo '<li class="dropdown-item dropdown"><a class="dropdown-toggle" id="dropdown2-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . $item['name'] . '</a>';
                    sub_sub_menu1($array, $item['menu_id']);
                    echo '</li>';
                }
            }
            echo "</ul>";
        }
    }
    
    function sub_sub_menu1($array = array(), $parent_id = false) {
        if(!empty($array[$parent_id])) {
            echo '<ul class="dropdown-menu" aria-labelledby="dropdown2-1">';
            foreach ($array[$parent_id] as $item) {
                if ($item['dropdown'] == false) {
                    echo '<li class="dropdown-item"><a href="' . $item['href'] . '">' . $item['name'] . '</a></li>';
                }
            }
            echo "</ul>";
        }
    }
    ?>
    <div class="navbar navbar-expand-md navbar-dark bg-dark mb-4" role="navigation">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarCollapse">
            <ul class="navbar-nav mr-auto">
                <?=menu_builder1($db, 0)?>
            </ul>
        </div>
    </div>
    

    also some SQL info

    CREATE TABLE `menu` (
        `menu_id` int(11) NOT NULL,
        `menu_sub_id` int(11) NOT NULL,
        `added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        `status` int(1) NOT NULL DEFAULT '1',
        `href` varchar(150) NOT NULL,
        `class` varchar(150) NOT NULL,
        `position` int(3) NOT NULL,
        `name` varchar(150) NOT NULL,
        `description` varchar(500) NOT NULL,
        `dropdown` int(11) NOT NULL,
        `sub_menu` int(1) NOT NULL,
        `sub_sub_menu` int(1) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    ALTER TABLE `menu`
        ADD PRIMARY KEY (`menu_id`);
    
    ALTER TABLE `menu`
        MODIFY `menu_id` int(11) NOT NULL AUTO_INCREMENT;
    COMMIT;
    

    这篇关于带有子菜单的 PHP Bootstrap 4 导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-26 09:24