简体   繁体   中英

pictures with Javascript from array

EDIT: I have followed the advice of Happy and Bart Friederichs and it has been really helpful. Instead of using php i am using javascript and the code is now working, but i still have an issue. When I click the button on the page it displays the pic that i want but the button disappears, so i cant cycle though the rest of the pictures in the array. What going on? Any help would be appreciated.

<html>
<head>
<script type="text/javascript"> 
var picArray=["images.jpg","customLogo.gif.png"];
var count=0;

function changePic(){
    document.write("<img src='"+ picArray[count] +"' />");
    count++;
}
</script>
</head>

<body>
    <button type="button" onclick="changePic()">Click Me!</button>
</body>
</html>

You need to use ajax to handle the onClick event, this in turn would run a PHP page in the background which could return it a filenmae.

Then ajax / jQuery would change the actual pic

Here is a tutorial covering ajax with php: http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php

Alternatively you can output all the filenames to a java script array:

echo '<script> var picarray = array() ;';
foreach($arrayPic as $pic) ...

Then just access it using js

Your changePic() function is a PHP function however when you call onclick="changePic()" you are using HTML to call a Javascript function. If you looked at your debug window in your browser you would see an error saying that changePic does not exist.

You can not use html's onClick to call a PHP, not without either redirecting or calling 'wrapper' function in JS that loads your PHP file with arguments via AJAX and so forth.

You have a few options here.. either put your images into a Javascript array and use the onclick call to grab them from that, if your doing that, you do not even need your iframe you can just print the image directly to the page using document.write . Or, why not just set the source of the iframe to your PHP script with an argument for the array index. So where you have

src=$picArray[count]

Change to

src=whatever.php?image=1

For example. This way would only need to render the iframe once rather than on every click like you are attempting to know, you would just be changing the iframe content.

There are a heap of ways to do what you are trying, let me know if either of the above suggestions work for you.

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