保存DOM元素供以后使用

时间:2015-12-06 18:19:03

标签: javascript html

我有一个

  

输入类型="按钮"

我的HTML代码中的

元素。我打电话给" onclick"该按钮上的方法,但我收到以下错误

  

未捕获的TypeError:无法设置属性' onclick'为null

我认为变量按钮为空,因此我无法调用" onclick"对某些东西的方法是null。我不知道为什么这是空的。



public int getAllCandidatesUsing8(int num) {
    final int[] cnt = {0};
    int pow = (int) Math.pow(2, num);
    IntStream.range(0, pow).parallel()
            .forEach(i -> {
                //computing codes
                cnt[0]++;
            });
    return cnt[0];
}

alert("Bine ati venit!");

var button = document.getElementById("buton");

button.onclick = function(){

	var luna = document.getElementsByName("luna")[0].value;
	var zi = document.getElementsByName("zi")[0].value;
	var zodie;
	
	if((luna == 1 && zi <= 20) || (luna == 12 && zi >= 22)){
		document.getElementsByName("zodie")[0].value = "Capricorn"
	}else if((luna == 1 && zi >= 21) || (luna == 2 && zi <= 18)){
		document.getElementsByName("zodie")[0].value = "Varsator";
	}else if((luna == 2 && zi >= 19) || (luna == 3 && zi <= 20)){
		document.getElementsByName("zodie")[0].value = "Pesti";
	}else if((luna == 3 && zi >= 21) || (luna == 4 && zi <= 20)){
		document.getElementsByName("zodie")[0].value = "Berbec";
	}else if((luna == 4 && zi >= 21) || (luna == 5 && zi <= 21)){
		document.getElementsByName("zodie")[0].value = "Taur";
	}else if((luna == 5 && zi >= 22) || (luna == 6 && zi <= 21)){
		document.getElementsByName("zodie")[0].value = "Gemeni";
	}else if((luna == 6 && zi >= 22) || (luna == 7 && zi <= 21)){
		document.getElementsByName("zodie")[0].value = "Rac";
	}else if((luna == 7 && zi >= 22) || (luna == 8 && zi <= 22)){
		document.getElementsByName("zodie")[0].value = "Leu";
	}else if((luna == 8 && zi >= 23) || (luna == 9 && zi <= 22)){
		document.getElementsByName("zodie")[0].value = "Fecioara";
	}else if((luna == 9 && zi >= 23) || (luna == 10 && zi <= 22)){
		document.getElementsByName("zodie")[0].value = "Balanta";
	}else if((luna == 10 && zi >= 23) || (luna == 11 && zi <= 21)){
		document.getElementsByName("zodie")[0].value = "Scorpion";
	}else if((luna == 11 && zi >= 22) || (luna == 12 && zi <= 21)){
		document.getElementsByName("zodie")[0].value = "Sagetator";
	}
};

window.onbeforeunload = function(){
	return "La revedere!";
};
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

如果您的按钮的id不是button,那么您无法获得

document.getElementById("buton");

为该按钮添加ID

<input type="button" id="my-button"/>

然后

var button = document.getElementById('my-button');

编辑好的,然后将<script>放在页面末尾<body>