Javascript Global Variables

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script type="text/javascript">
var toggle;
toggle=1;
function open(){
jQuery(window).bind("beforeunload", function(){$.post("logout.php");})
$.post("online.php",function(data){
$("#Layer6").html(data);
});
}

function toggle() 
{
$("#Layer4").animate({height:'toggle'});
$("#Layer6").animate({height:'toggle'});

if(toggle==1)
{
$("#toggle").attr('src',"toggle_up.jpg");
toggle=0;
}
else
{
$("#toggle").attr('src',"toggle_down.jpg");
toggle=1; 
}  

}

</script>

Here I defined toggle as a global variable and first set its value to 1. When toggle () is executed, the toggle value should change as its global variable. When executed, the script does not seem to work at all (part of the switch).

Kindly help. Thank!

+3
source share
2 answers

You named your variable and function with the same name ("switch"). A function definition overrides your variable declaration (since it comes after that). Rename your function to something else, for example. doToggle().

, , , Javascript. , , Javascript , , :

var variable = 3;
variable = function() { alert('Function called') };
variable();     // Calls the function, whose reference is stored in 'variable'
+3

, , .

, , jQuery .toggle()... , $ jQuery... -, .

, :

var count = 1;

function toggle() 
{

    $("#Layer4").animate({height:'toggle'});
    $("#Layer6").animate({height:'toggle'});

    $("#toggle").attr('src',"toggle_" + (count++ % 2 ? "up" : "down") + ".jpg");

}

jsFiddle


Javascript, up down src #toggle.

(count++ % 2 ? "up" : "down") count ( ) 2. 1, 0. 1 (true), up . 0 (false), down . - .

, jQuery/ , , , .

(function() { 
    var count = 1;
    function open() { ... }
    function toggle() { ... }
    $(function() {
        ...
    });
}());
0

Source: https://habr.com/ru/post/1767714/


All Articles