【问题标题】:How to style html elements in javascript output in php如何在 php 中的 javascript 输出中设置 html 元素的样式
【发布时间】:2021-08-06 00:35:31
【问题描述】:

我正在编写的代码有问题,需要一些帮助。我正在尝试设置样式并将类和 id 附加到一些 html 元素。这些 html 元素是 javascript 输出。并且 javascript 代码嵌入在 php 标签中。

我已经以不同的方式尝试过,但我大多遇到引号问题

<?php
echo '<script>
function newLength{
document.getElementsByClassName('listarea')[0].innerHTML = "<div style='height:auto; width:auto;' class='item' id='bgitem'><span class='pull-right' onclick='myClose(this);'><i class='fa fa-times' style='cursor:pointer'></i></span>";
}
</script>';
?>

您会注意到,由于 classidstyle 选项,此代码不会运行。我知道可以删除样式,但其他样式需要存在。我在 php 中使用 while 循环,因此每个循环的脚本都不同。处理这种情况的最佳方法是什么。我是初学者,所以我非常感谢帮助。提前致谢

【问题讨论】:

  • 跳出 PHP 块而不是回显它。你的引号把一切都搞砸了,而且你没有在其中使用任何变量。

标签: javascript php html css mysql


【解决方案1】:

您可以在&lt;php&gt; 块之外添加脚本,从而更轻松地解决引用问题:

<?php
  # do PHP stuff
?>

<script>
  function newLength{
    document.getElementsByClassName('listarea')[0]
      .innerHTML = "<div style='height:auto; width:auto;' class='item' id='bgitem'><span class='pull-right' onclick='myClose(this);'> <i class='fa fa-times' style='cursor:pointer'></i></span>";
  }
</script>;

【讨论】:

  • 正如我之前所说,我正在使用 while 循环,因此脚本不能在 php 块之外
  • @MichaelDavid 是的,它可以。 while(1) { ?&gt; html stuff here &lt;?php } 是完全有效的语法。
【解决方案2】:

使用\ 转义它们:

echo '<script>
function newLength{
document.getElementsByClassName(\'listarea\')[0].innerHTML = "<div style=\'height:auto; width:auto;\' class=\'item\' id=\'bgitem\'><span class=\'pull-right\' onclick=\'myClose(this);\'><i class=\'fa fa-times\' style=\'cursor:pointer\'></i></span>";
}
</script>';

顺便说一句,如果你使用双引号作为回声,你只需要在 div 之前转义一个

【讨论】:

    【解决方案3】:

    你可以把代码放在php标签外面。

    <?php
    //PHP Codes
    ?>
    Your JS / HTML code
    <?php
    //PHP Codes
    ?>
    

    【讨论】:

    • 请澄清答案,否则你会被否决
    猜你喜欢
    • 2010-09-25
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多