javascript - 网页改了一次后如何刷新?

标签 javascript html refresh webpage

 

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");

在第一种情况下,当您第二次尝试更改项目的 valid - 它已经有另一个 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/

相关文章:

javascript - 我正在尝试在 javascript 中制作一个简单的切换按钮

javascript - 未捕获的语法错误 : Invalid regular expression: missing forwardslash(/)

javascript - 将 JS 数组值添加到多个 div

javascript - 使用onclick在同一图像上播放和暂停

css - 刷新/重新计算 css

ios - 进行更改后,Xcode Storyboard不会刷新

javascript - 防止使用 JavaScript 刷新/重新加载页面

javascript - jQuery 多个元素的高级选择器

html - CSS 未在实时网站上显示

html - :table-cell determined的padding是怎么显示的