Uncaught referenceError: $counter is not defined

Uncaught referenceError: $counter is not defined

我的 JS 文件中有一个函数,我想通过一个名为 $counter 的 PHP 变量给出一个值。我得到一个错误:$counter 未定义。

这是 PHP-代码:

<?php
$counter = 0;

foreach($res as $category){                    
  echo '<div class="category" onmouseover="doChangeFontWeight($counter);" onmouseout="undoChangeFontWeight($counter);">';
  echo '<p class="categoryDescription">'.utf8_encode($category['description']).'</p>';
  echo '</div>';

  $counter++;
}
?>

Javascript:

function doChangeFontWeight(counter) {
"use strict";

document.getElementsByClassName("categoryDescription")[counter].setAttribute("style", "font-weight: 900");}
'<div class="category" onmouseover="doChangeFontWeight('.$counter.');" onmouseout="undoChangeFontWeight('.$counter.');">';

在 PHP.

中,变量未在单引号内传递

您可能想尝试使用双引号而不是单引号来回显。

echo "<div class='category' onmouseover='doChangeFontWeight($counter);' onmouseout='undoChangeFontWeight($counter);'>";
echo "<p class='categoryDescription'>".utf8_encode($category['description'])."</p>";
echo "</div>";