can somebody help why i get this error?
Uncaught ReferenceError: selected_1 is not defined
Uncaught ReferenceError: selected_2 is not defined
Here is my code:
<img src="/css/img/firstRoom_selected.png" onclick="selected_1()" id="firstRoom" style="cursor:pointer;">
<img src="/css/img/secondRoom.png" onclick="selected_2()" style=" cursor:pointer;">
<script>
$( document ).ready(function() {
function selected_1() {
if (document.getElementById("firstRoom").src == "/css/img/firstRoom.png")
{
document.getElementById("firstRoom").src = "/css/img/firstRoom_selected.png";
}
}
function selected_2() {
if (document.getElementById("firstRoom").src == "/css/img/firstRoom_selected.png")
{
document.getElementById("firstRoom").src = "/css/img/firstRoom.png";
document.getElementById("secondRoom").src = "/css/img/secondRoom_selected.png";
}
}
});
</script>
Thanks a lot in advance! :)
Your no need to use $( document ).ready
<img src="/css/img/firstRoom_selected.png" onclick="selected_1()" id="firstRoom" style="cursor:pointer;">
<img src="/css/img/secondRoom.png" onclick="selected_2()" style=" cursor:pointer;">
And js:
<script>
function selected_1() {
if (document.getElementById("firstRoom").src == "/css/img/firstRoom.png")
{
document.getElementById("firstRoom").src = "/css/img/firstRoom_selected.png";
}
}
function selected_2() {
if (document.getElementById("firstRoom").src == "/css/img/firstRoom_selected.png")
{
document.getElementById("firstRoom").src = "/css/img/firstRoom.png";
document.getElementById("secondRoom").src = "/css/img/secondRoom_selected.png";
}
}
</script>
It'd be better to do it like this:
$(function(){
$('#firstRoom').click(selected_1)
})
You've defined your functions inside another anonymous function using $document.ready
, hence it's not visible to the global scope.
Your images are looking for selected_1
and selected_2
in the global scope and hence couldn't find it.
define your function outside $(document).ready
handler
if you wish to use functions within handler then attach click handlers within ready function. try this script
you should also look into preloading images, that will be another question.
<script>
function selected_1() {
if (document.getElementById("firstRoom").src == "/css/img/firstRoom.png") {
var image = new Image()
image.src = "/css/img/firstRoom_selected.png";
document.getElementById("firstRoom").src = image.src
}
}
function selected_2() {
if (document.getElementById("firstRoom").src == "/css/img/firstRoom_selected.png") {
var image = new Image()
image.src = "/css/img/firstRoom.png";
document.getElementById("firstRoom").src = image.src
var image2 = new Image()
image2.src = "/css/img/secondRoom_selected.png";
document.getElementById("secondRoom").src = image2.src
}
}
</script>
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.