【问题标题】:PHP - Echoing a string as a parameter in a JavaScript onclick functionPHP - 在 JavaScript onclick 函数中将字符串作为参数回显
【发布时间】:2021-08-08 06:48:59
【问题描述】:

我正在尝试将 PHP 中的字符串作为 JavaScript 函数中的字符串变量回显。它没有按需要输出。我该如何解决这个问题?

<?php
    $example1 = "example 1";
    $example2 = "example 2";
    $example3 = "example 3';
    $string = $example1.", ".$example2.", ".$example3;
    echo "<script>function testFunction(string) {console.log(string);}</script>";
    echo "<button onclick='testFunction(".$string.")'>Test</button>";
?>

所需输出:&lt;button onclick='testFunction("example 1, example 2, example 3")'&gt;Test&lt;/button&gt;

实际输出:&lt;button onclick='testFunction("example 1" example 2= example 3=)'&gt;Test&lt;/button&gt;

【问题讨论】:

  • 更好的方法:完全避免内联处理程序,它们太可怕了
  • 我应该如何将唯一数据从 PHP 传递到 HTML 中的特定按钮以使用该数据执行 JavaScript?
  • 我更喜欢 &lt;script 标签中的 JSON,或者数据属性,或者单独的网络请求。如何构建它取决于解决方案的通用性 - 例如,如果您有多个按钮
  • 我确实有多个按钮,每个按钮都有自己独特的字符串参数。那么在按钮上放置一个数据属性,该属性对应于脚本标签中 JSON 数据中的字符串?还是将数据设为数据属性?

标签: javascript php html string echo


【解决方案1】:

内联处理程序是可怕的做法。他们有非常丑陋的引用转义问题(你在这里遇到)并且有一个疯狂的范围链。没有理由在现代 JavaScript 中使用它们。考虑以其他方式将值传递给 HTML,然后使用 JavaScript 正确附加处理程序。

例如,您可以为每个按钮使用数据属性,或者您可以将 JSON 回显到包含参数的脚本标记中:

$button_data = array(
    'example 1, example 2, example 3'
    // add more button data here as needed
);
<script type="button-data">
<?php echo json_encode($button_data) ?>;
</script>

然后在JS中读取并附加监听器:

const buttonData = document.querySelector('script[type="button-data"]');
// change this selector as needed
// to select only the buttons you care about
const buttons = document.querySelectorAll('button');
buttons.forEach((button, i) => {
  button.addEventListener('click', () => {
    testFunction(buttonData[i]);
  });
});

【讨论】:

    【解决方案2】:

    你可以使用下面的代码来做。

    <?php
    $example1 = "example 1";
    $example2 = "example 2";
    $example3 = "example 3";
    $string = $example1 . ", " . $example2 . ", " . $example3;
    ?>
    <script>
    function testFunction(string)
    {
        console.log(string);
    }
    </script>
    <button onclick='testFunction("<?php echo $string; ?>")'>Test</button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 2021-07-24
      • 1970-01-01
      • 2012-03-27
      • 2016-08-08
      • 1970-01-01
      • 2014-05-25
      • 2018-03-14
      相关资源
      最近更新 更多