function change(){
item = document.getElementById("first");
item.value = "second";
item.id = "second";
}
ob = document.getElementById("first");
ob.addEventListener("click",change);
<input id="first" type="button" value="first">
当你点击输入的时候,它变成了:
<input id="second" type="button" value="second">
我的需求是写javascript代码,当你点击id为second
的input时,网页会刷新。也就是说,改变当前输入元素:
<input id="second" type="button" value="second">
进入上一个:
<input id="first" type="button" value="first">
这是我的尝试:
function change(){
item = document.getElementById("first");
item.value = "second";
item.id = "second";
}
ob = document.getElementById("first");
ob.addEventListener("click",change);
function previous(){
document.execCommand('Refresh')
}
ob = document.getElementById("second");
ob.addEventListener("click",previous);
<input id="first" type="button" value="first">
error: Uncaught TypeError: Cannot read property 'addEventListener' of null
at line27.
最佳答案
实际上无法理解,为什么您需要这样一种晦涩的方式来执行此操作以及 .execCommand("Refresh")
甚至应该意味着什么 - execCommand
文档甚至没有将 refresh
列为选项,但是,您的错误是由这些行引起的:
item = document.getElementById("first");
ob = document.getElementById("second");
在第一种情况下,当您第二次尝试更改项目的 val
和 id
- 它已经有另一个 id
(已更改通过第一个函数使用)
在第二种情况下,您尝试将事件监听器绑定(bind)到该行执行时页面上不存在的元素。
如果我是你,我会这样写(假设出于某种原因你真的需要更改对象的 id):
ob = document.getElementById('first');
ob.addEventListener('click',function(){
if (this.id=='first') {
this.id = 'second';
this.value = 'second';
} else {
location.reload();
}
});
<input id="first" type="button" value="first">
关于javascript - 网页改了一次后如何刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735251/