onclick不更新。即使使用.onclick =“ hideList()”,仍显示旧值;

时间:2019-01-26 09:10:21

标签: javascript onclick

onclick的值不会被替换。控制台窗口显示为未更改。 这是JavaScript代码:

function viewList(){
  var c=document.querySelector(".list");
  c.style.display= "block";
  document.querySelector(".box").style.height="700px";
  document.getElementById("btn").onclick="hideList()";
  console.log(document.getElementById("btn"));
}
function val(p){
  var i=document.getElementsByClassName("valued");
  var j=document.createAttribute("value");
  j.value=p.textContent;
  i[0].setAttributeNode(j);
}       
function hideList(){
  var c=document.querySelector(".list");
  c.style.display= "none";
  document.querySelector(".box").style.height="500px";
}

1 个答案:

答案 0 :(得分:2)

//if you want to set string at function use this way
document.getElementById("btn").setAttribute('onclick',"hideList()");
//if you want set function variable then 
document.getElementById("btn").onclick=hideList;

更新:

//This will set the method to a string
document.getElementById("btn").onclick="hideList()";