[英]When trying to dynamically add table elements using JavaScript via innerHTML doesn't render in IE7, IE8 and IE9
I've been searching the interweb a bunch for this one and I'm stumped. 我一直在互联网上搜索一堆,但很困惑。 The following Javascript works in Chrome, Firefox, and Safari, but for whatever reason it is not working in IE 7+. 以下Javascript可在Chrome,Firefox和Safari中使用,但无论出于何种原因,它都无法在IE 7+中运行。 What I mean by 'not working' is that when trying to add table elements, nothing shows up in the browser / on the screen. 我的意思是“不工作”是,当尝试添加表元素时,浏览器/屏幕上没有任何显示。 I've used IE's built-in Developer tools, and nothing shows up on the de-bugger in the Console. 我已经使用了IE的内置开发人员工具,但在控制台的调试器中没有任何显示。
In a nutshell, all I'm trying to do is create table rows that have a checkbox in the first column, and plain text in the second column. 简而言之,我要做的就是创建表行,该行在第一列中具有一个复选框,在第二列中具有纯文本。 Also, this entire method is being called after an AJAX event. 同样,在AJAX事件后将调用整个方法。
Here is the code: 这是代码:
tdObjs[0].innerHTML = '<input type="checkbox" name="page" value="' + pageID + '"
onClick="fooFunction(\'' + pageID + '\', this,
\'_images/foo/' + pageID + '.png\', \'' + pageID
+ '\')" checked="yes">';
Where pageID
is a variable passed to this function (in this exact example, its an int
value of 5
). 其中pageID
是传递给此函数的变量(在此示例中,其int
值为5
)。 tdObjs
is defined by: tdObjs
的定义是:
var tdObjs = trObj.getElementsByTagName('TD');
And trObj
is passed into this function. 然后将trObj
传递给此函数。 trObj
does show up in the local
window of the IE Developer Tools as it is defined in another function like so: trObj
确实显示在IE开发人员工具的local
窗口中,因为它是在另一个函数中定义的,如下所示:
var tableObj = $('##FooTable')[0];
var trObj = document.createElement('tr');
trObj.appendChild(document.createElement('td'));
for (var i=0;i<2;i++)
trObj.appendChild(document.createElement('td'));
tableObj.appendChild(trObj);
return trObj;
Any ideas? 有任何想法吗? Thank you in advance. 先感谢您。
When adding rows to a table in IE, you must add them to the tbody, eg 在IE中向表中添加行时,必须将它们添加到tbody中,例如
<table id="foo">
<tr>
<td>cell 0
<td>cell 1
</table>
In the above HTML, browsers will add a tbody element between the table and row elements. 在上述HTML中,浏览器将在表元素和行元素之间添加一个tbody元素。 The tbody is mandatory but tags are optional. tbody是必需的,但标签是可选的。 So to add rows you must do something like: 因此,要添加行,您必须执行以下操作:
var table = document.getElementById('foo');
var tbody = table.tBodies[0];
var row = document.createElement('tr');
var cell = document.createElement('td');
// Give cell some content and add it
cell.appendChild(document.createTextNode('cell 0'));
row.appendChild(cell);
// Make another cell and add it
cell = cell.cloneNode(false);
cell.appendChild(document.createTextNode('cell 1'));
row.appendChild(cell);
tbody.appendChild(row);
It may be more efficient to clone a row and modify the cell contents rather than making new rows and cells. 克隆行并修改单元格内容可能比创建新的行和单元格更为有效。 It's up to you. 由你决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.