简体   繁体   中英

Pass variable from php while loop to javascript function

I have some images and what i want to do is on mouse over each pic to change a text inside a div which is the image title.

So here's my code:

<?php
...

$i=0;
while($i<$imageno)
{

echo'
<script type="text/javascript">
function changeText() {document.getElementById("title").innerHTML = "'.$title[$i].'";}
</script>';

if ($imagine[$i]){
echo '<div onmouseover="changeText()"><img src="'.$imagine[$i].'"></div>';
};
$i++;
}

...
?>

But my script shows only the tscription of my last picture...

Please help! ...without Ajax

You need to pass variable to changeText function:

echo '<div onmouseover="changeText('".$title[$i]."')"><img src="'.$imagine[$i].'"></div>';

And to change changeText function like this:

function changeText( myText ) {document.getElementById("title").innerHTML = myText;}

You don't need to put the function definition in the loop, and you need to use parameter.

<script type="text/javascript">
function changeText(title) {document.getElementById("title").innerHTML = title;}
</script>

<?php
//... 
$i=0;
while($i<$imageno) {
  if ($imagine[$i]){
    $title = json_encode(htmlspecialchars($title[$i]));
    echo '<div onmouseover="changeText('.$title.')"><img src="'.$imagine[$i].'"></div>';
  };
  $i++;
}
//...
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM