HTML“onclick” JavaScript中的事件(在一个表中) [英] HTML "onclick" event in JavaScript (In a table)
问题描述
我试图将我用HTML编写的表格转换成Javascript,因为我想要动态生成表格(行数)。我遇到的主要问题是表格中的单个单元格可点击并打开另一个html页面。不幸的是,HTMLonclick参数不适用于 document.write
语句下面是HTML表格单元格的示例:
< td id =r1c1align =centeronclick =getTicket(1,'plan',1);>< script language = JavaScript> document.write(getDate(1,plan,r1c1)); < /脚本>< / TD>
这行中的函数是预定义的,因此我不会发布这些函数,但是想法是,功能 getTicket(..)是假设打开另一个HTML页面。
我的问题是如何让onclick在JavaScript中工作。我可以使用document.write命令在JavaScript中创建单元格,但不知道如何使这些单元格可点击以运行 getTicket(..)。
。至少可以说,您的Javascript编程风格是古代的。 document.write
是一个主要在几乎没有常见方法生成动态内容时开发的函数。
你应该使用像 document.createElement
这样的方法动态地生成你的元素,在那里附加你的内容,然后用 appendChild
。
onclick
,比如 addEventListener
。这里有一个片段: var td = document.createElement(td);
td.innerHTML = getDate(1,plan,r1c1);
td.addEventListener(click,function(){
getTicket(1,'plan',1);
});
row.appendChild(td);
我认为 row
是
不幸的是,IE< 9使用了一种叫做 attachEvent
的不同方法,所以它'd变成:
td.attachEvent(onclick,function(){...
I'm trying to convert a table I've written in HTML into Javascript because I want the table to be dynamically generated (# of rows). The main issue I'm having is that the individual cells in the table are clickable and open up another html page. Unfortunately, the html "onclick" parameter doesn't work with document.write
statements Here is an examples of a table cell in HTML:
<td id="r1c1" align="center" onclick="getTicket(1,'plan',1);"><script language="JavaScript">document.write(getDate(1,"plan", "r1c1")); </script></td>
The functions in this line are predefined and work so I'm not going to post those, but the idea is that the function getTicket(..) is suppose to open up another html page.
My issues is how to get the onclick to work in JavaScript. I can create the cells in Javascript using document.write commands but don't really know how to make those cells clickable to run the function getTicket(..).
Your style of Javascript programming is ancient, to say the least. document.write
is a function developed mainly when there were almost no common methods to generate dynamic content.
So, you should generate your elements dynamically with methods like document.createElement
, append your content there, then attach the elements to the DOM with modern methods like appendChild
.
Then, you can attach event listeners using something more modern than the traditional way like onclick
, like addEventListener
. Here's a snippet:
var td = document.createElement("td");
td.innerHTML = getDate(1, "plan", "r1c1");
td.addEventListener("click", function() {
getTicket(1, 'plan', 1);
});
row.appendChild(td);
I supposed that row
is the row of the table that you're generating.
Unfortunately, IE<9 uses a different method called attachEvent
, so it'd become:
td.attachEvent("onclick", function() { ...
这篇关于HTML“onclick” JavaScript中的事件(在一个表中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!