JavaScript + foreach PHP ...我找不到错[关闭]

Hello, I have problem with my JS function. Please help me, I need this code until today and I can't understand what is the wrong :(

  foreach($group as $i => $name){
   print'<li onclick="groups(\'group'.$i.'\');" >'.$name.'</li>';
}

Then I have this code:

$moretags = "<script>";
$moretags .= 'function groups(grid){';
  foreach($group as $i => $name){
  $moretags .= '
  if(grid == \'group'.$i.'\'){
  document.getElementById(\'show\').innerHTML = \'group'.$i.'\';
  }
  ';

}


$moretags .= '</script>';

I completely agree with Felix Kling that you shouldn't generate JavaScript code with PHP code unless you really know what you're doing, which you apparently do not.

It is impossible to solve your problem because of the lack of details in your question but I'll try to at least help you make your code less error prone.

All you should generate in your PHP should be the HTML tags (at most!) without any onclick attributes, only classes and maybe some ids. Then just add the relevant event handlers in JavaScript (and use some framework like jQuery - read this to see why) or you can even add the HTML elements in JavaScript if they can't be used without JavaScript anyway.

Code generation is a hard thing. Generating JavaScript in PHP won't get you very far.

The proper way to do this would be to make an array or object in PHP with all of the data you need to pass to JavaScript on the client side.

$groups = array('some', 'elements', 'here');

Then, output it to your page:

<script>
    var groups = <?php echo json_encode($groups); ?>;
</script>

Then, you have full access to the data in JavaScript without having to dynamically generate the script as you are now. The only part you have to generate is the assignment of variables.