drxp993551 2016-06-16 05:47
浏览 82

将PHP字符串变量传递给Javascript函数

I have a Javascript function which changes the background color of a DIV ID. I just send it the DIV ID and the Color. changeBG(DivID, Color)

I would like the Div ID to be a variable, so I can set the variable and then call the function. It works fine if I hard code the literal string of the Div ID - 'floorData2" in the example below. I have a PHP variable ($floorDiv) which contains the Div ID and would like to replace 'floorData2' with $floorDiv in the call to the changeBG() function.

I have tried single quotes, double quotes, escaped quotes in every combination I can think of. I still can't make it work. What is the correct syntax to use the variable $floorDiv?

<?php
    $floorCount =5;
    $floorNow = 1;
    while ( $floorNow <= $floorCount) {
        $floorDiv = 'floorData1'; /* this will change based on floorNow */
    echo '<div class="FloorH">
            &nbsp;First Floor <button onclick="changeBG(\'floorData2\',\'#F0F\');">Magenta</button>
    </div>';
    echo "<div id='floorData$floorNow'>";

    echo "</div>";
    $floorNow = $floorNow + 1;
    }
    ?>
  • 写回答

6条回答 默认 最新

  • duanfang2708 2016-06-16 05:52
    关注

    PHP alternative syntax is much easier for HTML templating

    <?php for ($floorNow = 1; $floorNow <= 5; $floorNow++) :
          $floorDiv = 'floorData' . $floorNow;
    ?>
        <div class="FloorH">
            &nbsp;First Floor
            <button value="<?= htmlspecialchars($floorDiv) ?>" 
                    onclick="changeBG(this.value, '#F0F')">Magenta</button>
        </div>
        <div id="<?= $floorDiv ?>"></div>
    <?php endfor ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)