如何优化这个PHP / JS代码[关闭]

Header.php

<?
$req = mysql_query('SELECT * FROM Groupe ORDER BY Groupe_Ordre ASC');

while($myrow = mysql_fetch_array($req))
{
$Groupe_id = $myrow['Groupe_id'] ;

echo "<div class='Sous-Menu' name='Sous-Menu-$Groupe_id'></div>";
}
?>

Script.js

$("div[name='Groupe-7']").mouseover(function(){ 
   $('.Sous-Menu').hide(); 
   $("div[name='Sous-Menu-7']").show(00); 
});

$("div[name='Groupe-8']").mouseover(function(){ 
   $('.Sous-Menu').hide(); 
   $("div[name='Sous-Menu-8']").show(00); 
});

...

Hello StackOverFlow,

In the page "Script.js", i have a very lot of repetitive line for each "Groupe".

How I can automate "Script.js"?

I think the best you could to in terms of optimization is to attach a single event to listen for a group of elements and store a reference value to a data-attr.

Your html element would look like this:

<div class='Sous-Menu' data-groupe='Sous-Menu-7'></div>

Your js would look like this:

// note if you are using a ref twice
// make sure you cach it into a var 
// so jquery does not have to parse the dom
// twice to search for the same thing
var $sousMenu = $('.Sous-Menu');

$sousMenu.mouseover(function() {
  var $this = $(this); // get element ref
  var groupe = $this.data('groupe'); // get the group attr from the el

  $sousMenu.hide(); 

  // your code here ... if (groupe == 'Sous...')
});

Your js will improve its performance, reducing the number of events and preventing jquery from non necessary dom transversing.

  • Quick note on your php, make sure to use PDO instead of mysql_query as it does not have support any longer and it will deprecated from future versions.

Hope it solves your issue, cheers!