Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

javascript - Add onclick event programmatically

How do I add an onclick event to a tag in HTML programmatically?

I want to be able to click a link, and have an onclick event attached to a Javascript function take effect on another tag.

Here is what I have so far:

var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount); 
var cell1 = row.insertCell(0); 
var element1 = document.createElement("input");
element1.type = "text";
element1.id="List["+num+"].id";
element1.name="List["+num+"].id";
element1.onclick="javascript:CalCal()";
cell1.appendChild(element1);

I want to call a Javascript function CalCal() on onClick event. Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

But keep in mind that addEventListener is supported in IE just from version 9. To support older versions of IE you could use something like that:

if (element1.addEventListener) {  // all browsers except IE before version 9
  element1.addEventListener("click", CalCal, false);
} else {
  if (element1.attachEvent) {   // IE before version 9
    element1.attachEvent("click", CalCal);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...