我是javascript新手,对以下问题相当困惑:
在我单击按钮之前,可以检测到按键并发出警报
但是,单击按钮后,页面会继续加载,并且不再检测到按键,我想问一下为什么会发生?我的代码有什么错误?(请注意:即使我使用2个diff函数进行两次打印,也存在相同的问题)
这是我的代码:
<script type="text/javascript">
document.onkeypress = function(cde) {
cde = cde || window.cde;
alert ("some key pressed");
}
function abc(tester) {
if (tester == 0){
document.writeln("<button onClick=\"abc(1);\" >To T1</button>")
document.writeln("tester0")
}
if (tester == 1){
document.writeln("tester1")
}
}
abc(0);
</script>
使用马拉卡代码后(问题仍然存在):
<script type="text/javascript">
document.onkeypress = function(cde) {
cde = cde || window.cde;
alert ('some key pressed');
}
var tester = 0;
function switchTester() {
var b = document.getElementById('switch-btn');
b.innerHTML = 'To T' + tester;
tester = 1 - tester;
if (tester==0)document.writeln('a list of html content A');
if (tester==1)document.writeln('B a list of html content B');
}
document.body.innerHTML='';
</script>
<button id="switch-btn" onClick="switchTester();">To T1</button>
再次,马拉卡(Thz Maraca),他的脚本帮助切换了html固定内容,但是如果内容具有某些变量该怎么办?喜欢分数/天气等?
马拉卡代码:
<script>
document.onkeypress = function(cde) {
cde = cde || window.cde;
alert ('some key pressed');
}
var state = 0;
function toggle() {
document.getElementById('toggle-btn').innerHTML = 'switch to state ' + state;
var t = document.getElementsByClassName('toggle-content');
t[state].style.display = 'none';
state = 1 - state;
t[state].style.display = 'block';
}
</script>
<div class="toggle-content">
<h1>default content</h1>
<p>bla bla bla</p>
</div>
<div class="toggle-content" style="display:none">
<h1>other content</h1>
<p>whatever</p>
</div>
<button id="toggle-btn" onclick="toggle()">switch to state 1</button
>
最佳答案
(添加信息后的新答案。)以下是实现切换按钮的方法,该按钮还可以切换内容:
http://jsfiddle.net/sjq5ts5q/(仅当显示内容的框架具有焦点时才注册关键事件)
<script>
document.onkeypress = function(cde) {
cde = cde || window.cde;
alert ('some key pressed');
}
var state = 0;
function toggle() {
document.getElementById('toggle-btn').innerHTML = 'switch to state ' + state;
var t = document.getElementsByClassName('toggle-content');
t[state].style.display = 'none';
state = 1 - state;
t[state].style.display = 'block';
}
</script>
<div class="toggle-content">
<h1>default content</h1>
<p>bla bla bla</p>
</div>
<div class="toggle-content" style="display:none">
<h1>other content</h1>
<p>whatever</p>
</div>
<button id="toggle-btn" onclick="toggle()">switch to state 1</button>
(旧答案。)我认为您想要做的是一个切换按钮:
<script type="text/javascript">
document.onkeypress = function(cde) {
cde = cde || window.cde;
alert ('some key pressed');
}
var tester = 0;
function switchTester() {
var b = document.getElementById('switch-btn');
b.innerHTML = 'To T' + tester;
tester = 1 - tester;
// if (tester == 0) do whatever you want to
}
</script>
<button id="switch-btn" onClick="switchTester();">To T1</button>
关于javascript - 在onclick(将调用一个函数)之后,它将继续加载并且无法检测到按键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29906739/