自动生成<div>标签到Html网页

时间:2015-12-27 15:45:15

标签: php html

我有这些代码行:

<div class="signals">
  <ul>
    <li><a href="#signal1" class="fancybox">First Signal</a></li>
    <li><a href="#signal2" class="fancybox">Second Signal</a></li>
    <li><a href="#signal3" class="fancybox">Third Signal</a></li>
  </ul>
</div>

<div id="signal1" style="display:none;">
  <p style="color:#fff">First comment for #signal1 id - it will open in a fancybox -.</p>
  <div id="signal2" style="display:none;">
    <p style="color:#fff">Second comment for #signal2 id - it will open in a fancybox -.</p>
  </div>
  <div id="signal3" style="display:none;">
    <p style="color:#fff">Third comment for #signal3 id - it will open in a fancybox -.</p>
  </div>

这是jsfiddle代码:JsFiddle

现在,当我想显示不同的评论时,我打开我的html文件并编辑“id #signal,在需要时添加更多ID(或删除它们)。” 问题是:信号可能超过三个,甚至更少 所以我的问题是:
有一种方法可以在第二张表格中自动生成我需要的div,我将在其中插入注释和所有id? (某种后端)
例如:如果有一天我只需要2个信号,我将创建#signal1和#signal2 div,我将插入注释并保存次要表。
当我这样做时,带有html内容的主要表格将显示2条“li”行:

  • First Signal
  • 第二信号
  • 当我点击它们时,fancybox将打开并显示注释,就像代码进入jsfiddle一样。

    我不太了解php,但有一种方法可以使用它吗?还是有更好的方法?
    希望我能从你的帮助中学习。

    1 个答案:

    答案 0 :(得分:0)

    似乎你需要PHP foreach循环。

    您可以在PHP数组中编写注释,并使用PHP foreach读取它们。

    以下是示例代码:

    <?php
        $commentsLabels = array('First Signal','Second Signal');
        $commentsTexts = array('First comment for #signal1 id - it will open in a fancybox.','Second comment for #signal2 id - it will open in a fancybox.');       
        //You could use a 2D array to store both comments Labels and comments Texts in one array, but since you are new to PHP, I put them in 2 different arrays to make it easy.
        //You can add more comments texts/labels to the arrays in double/single quotes separated with ','
        //For now, the arrays are filled manually. in future, you can add a DB to store comments and fetch the values from there.
    
        $counter = 0; 
        //we need a counter to make the comment ids dynamic
    ?>
    
    <!--GENERATING LABELS-->
    <div  class="signals"> 
        <ul>
    
        <?php
        foreach ($commentsLabels as $commentLabel) { //loop starts
            $counter++; //increasing $counter by 1, for each iteration      
            //We have to add HTML tags outside the php code block.
        ?>
                <li><a href="#signal<?php echo $counter; ?>" class="fancybox"><?php echo $commentLabel; ?></a></li> 
        <?php
            } //loop ends       
        ?>  
    
        </ul>
    </div>
    
    <!--GENERATING POPUPS-->
    <?php
        $counter = 0; //reset counter
    
        foreach ($commentsTexts as $commentText) { //loop starts
            $counter++; 
    ?>
            <div id="signal<?php echo $counter; ?>" style="display:none;"><p style="color:#fff"><?php echo $commentText; ?></p></div>
    <?php
        } //loop ends
    ?>
    

    我希望这有助于你开始。 : - )