如何在php foreach循环中添加额外的数据?

时间:2016-10-13 18:10:47

标签: php codeigniter

我正在使用CodeIgniter框架和pasing数组$ products来查看。在视图中我想为产品创建标签。以下是查看代码:

<ul class="tab">
    <?php foreach ($products as $products_item): ?>
        <li><a href="#" class="tablinks" onclick="openProduct(event, '<?= $products_item['product_id']; ?>')"><?=$products_item['product_id']?></a></li>
    <?php endforeach; ?>
    </ul>

    <?php foreach ($products as $products_item): ?>
        <div id="<?=$products_item['product_id']?>" class="tabcontent">
            <img src="<?php echo base_url(); ?>/uploads/<?php echo $products_item['image_url'];?>" /><br>   
            <?php echo $products_item['manufacturer']; ?><br>
            <?php echo $products_item['health']; ?>
        </div>
    <?php endforeach; ?>

    <script type="text/javascript">
        function openProduct(evt, productId) {
        // Declare all variables
        var i, tabcontent, tablinks;

        // Get all elements with class="tabcontent" and hide them
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }

        // Get all elements with class="tablinks" and remove the class "active"
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }

        // Show the current tab, and add an "active" class to the link that opened the tab
        document.getElementById(productId).style.display = "block";
        evt.currentTarget.className += " active";
        }
    </script>

效果很好,但没有默认选项卡。要添加默认选项卡,我需要添加

document.getElementById("defaultOpen").click();

到我的JS和id="defaultOpen"到第一个链接。我花了几个小时在这上面,无法理解......

1 个答案:

答案 0 :(得分:0)

  • 找不到。 $ products
  • 使用if标识第1个$ products,使其成为默认标签。