Because of variable hoisting in Javascript your script is ran as though it is:
$(function () {
var x;
if(typeof x == 'undefined') {
x = 0;
$("#dv").html(x);
} else if (x == 5) {
$("#dv").html(x);
}
});
So x
never equals undefined
so it never sets it to 0
. Note the variable x
in your function is a different variable to the variable x
in the page. This is because the variable in the script is closed over into the function scope.
If I'm understanding your problem correct I would do it this way:
<body data-x="5">
...
<div id="dv"></div>
$(function () {
var x;
if(typeof $('body').data('x') !== 'undefined') {
$("#dv").html($('body').data('x'));
} else {
$("#dv").html(0);
}
});