简体   繁体   中英

editing html with embedded PHP using javascript

I hope someone has an answer for me,

I am currently trying to create a PHP product page for my shop website, I have an sql table that stores the name of an image prefix eg if the image file is 'test_1.png' then the table stores 'test'. using embedded php

src="images/shop/<?php echo $row['item_img'], '_1.png';?>"></img>

what I would like to do is using js, dynamically update the src on a mouse click.

something like eg.

var imgSwitch = function(i){
  Document.getElementById('js-img').src = "images/shop/
    <?php echo $row['item_img'], '_';?>i<?php echo '.png';?>";
}

Even to me this seems wrong which is why I've turned to the GURU's here

Is there anyway this would be possible? If not, any suggestions would be GREATLY appreciated

I am trying to figure out what you are asking, and I think this is your way to go:

var imgSwitch = function(i){
  document.getElementById('js-img').src = "images/shop/<?php echo $row['item_img'], '_';?>" + i + ".png";
}

The change is in the i, you have to cut the string and add it as a variable.

But remember that the PHP code is executed at the server, and will not change once the page is sent to the client. When you execute that function, $row['item_img'] will always be the same.

A simple example which you can adapt. What I do in the code below is give the element an id and attach an onclick to it.

In the function we pass the id as a parameter ( onclick(changeSrc(this.id)) ) and we manipulate the src using the getElementById as we have the id .

<img src="http://ladiesloot.com/wp-content/uploads/2015/05/smiley-face-1-4-15.png" id="test" onclick="changeSrc(this.id);" height="400" width="400" />

<script>
function changeSrc(id) {
    document.getElementById(id).src = "http://i0.wp.com/www.compusurf.es/wordpress/wp-content/uploads/2014/04/smiley.jpeg?fit=1200%2C1200";
}
</script>

http://jsfiddle.net/tq1Lq5at/

Edit 1

You're using Document when it should be document , notice the lowercase d .

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