在代码中我尝试添加一个变量,我自己可以看到我出错的地方:
<!DOCTYPE html>
<html>
<body>
<h1>The * Operator</h1>
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var playerscore = playerscore + 1;
document.getElementById("demo").innerHTML = playerscore;
}
</script>
</body>
</html>
&#13;
答案 0 :(得分:1)
您需要声明playerscore
并将其设置为初始值,在这种情况下可能为0。像这样:
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
var playerscore = 0;
function myFunction() {
playerscore = playerscore + 1;
document.getElementById("demo").innerHTML = playerscore;
}
</script>
答案 1 :(得分:1)
playerscore
中的仅存在于函数内部。所以最初会undefined
。最简单的(though not necessarily the best way)是在global scope中定义变量。
//outside of function now in global scope (or window.playerscore)
//set it to a value (0) also. Otherwise it's undefined. undefined +1 is not going to work
var playerscore = 0;
function myFunction() {
//no var, the varibale is declared above NOT in here Important!
playerscore = playerscore + 1;
document.getElementById("demo").innerHTML = playerscore;
}
更好的选择是使用closure:
var myModule = (function(document){
//no longer in global scope. Scoped inside myModule so not publically accessible
var playerscore = 0;
function myFunction() {
//no var, the varibale is declared above NOT in here Important!
playerscore = playerscore + 1;
document.getElementById("demo").innerHTML = playerscore;
}
//allow myFunction to be called externally
return{myFunction:myFunction};
})(document);
HTML已针对上述内容进行了更改:
<button onclick="myModule.myFunction()">Try it</button>
虽然目前这可能有点过于先进。如果您对上述内容感兴趣,请阅读有关The Revealing Module Pattern
的内容答案 2 :(得分:0)
您正在尝试在初始化之前使用变量struct student
{
int rollno;
int standard;
char name[50];
char add[100];
int marks;
};
struct studentmarks
{
int rollno;
char name[50];
int marks;
};
。因此,它将是未定义的,并且递增非初始化变量是没有意义的,因此您不会在屏幕上看到任何内容。
所以,替换
wm = (WindowManager) content.getSystemService(Service.WINDOW_SERVICE);
orientationChanger = new LinearLayout(content);
orientationChanger.setClickable(false);
orientationChanger.setFocusable(false);
orientationChanger.setFocusableInTouchMode(false);
orientationChanger.setLongClickable(false);
orientationLayout = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
windowType, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.RGBA_8888);
wm.addView(orientationChanger, orientationLayout);
orientationChanger.setVisibility(View.GONE);
orientationLayout.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
wm.updateViewLayout(orientationChanger, orientationLayout);
orientationChanger.setVisibility(View.VISIBLE);
在palyerscore
放置之前:
var playerscore = playerscore + 1;
然后在myFunction()
内放置:
var playerscore = 0;