neko kao
neko kao

Reputation: 35

JavaScript cannot change image using attr

My html code here is to click next and change the graph. I have put 1.jpg, 2.jpg, 3.jpg, and html file into same file.

My question is that I want to change my graph by the code $("#page1").attr("src", fname);.

But it cannot do it at all. It always shows 1.jpg.


<script>
var order = new Array('1.jpg', '2.jpg', '3.jpg');
var trial = 0; //current trial
document.write("STRING:");
$(document).ready(function(){
 ShowImage(trial);
});

function ShowImage(t) {
 $("#page1").show();
 var N = t+1; //counting from 1
 $(".progress").text('('+N+'/'+order.length+')');
}

function NextImage() {
 current = current + 1;
 $("#page1").hide();
 var fname=order[current];
 $("#page1").attr("src", fname);
 });
 ShowImage(current);
}

</script>

<style> .page {display: none;} </style> 

<div class="page" id="page1">
<img src=1.jpg><br>
<input type=radio name=f1 value=T> T
<input type=radio name=f1 value=F> F <br>
<a href="javascript:NextTrial()">Next</a> 
<span class="progress"></span>
</div>

<div class="page" id="page2">
<h3>All done!</h3>
</div>```

Upvotes: 0

Views: 40

Answers (1)

Reza Sheykhi
Reza Sheykhi

Reputation: 797

you're going to change src of <img> tag, so you should get the <img> tag.
in your html the <img> tag is in <div id="page1"> so you should use the find keyword to get the <img> tag and then change the src of it.

function NextImage() {
 current = current + 1;
 $("#page1").hide();
 var fname=order[current];
 $("#page1").find('img').attr("src", fname);   //this line should find the img tag and then change the src attr
 });
 ShowImage(current);
}

Upvotes: 1

Related Questions