Javascript插入行
我有一个由几行组成的HTML表。我试图在表中的特定位置插入行。例如,如果我标记一个已经存在的行并单击“插入”,则应在下面插入一个新行。目前,在表的底部添加行是可行的。我需要的是在某个位置插入已经生成的行 这是我的密码:Javascript插入行,javascript,Javascript,我有一个由几行组成的HTML表。我试图在表中的特定位置插入行。例如,如果我标记一个已经存在的行并单击“插入”,则应在下面插入一个新行。目前,在表的底部添加行是可行的。我需要的是在某个位置插入已经生成的行 这是我的密码: function addLine(lineNumberGlobal,columnnumber,insertion) { var newrow = document.createElement("tr"); newrow.setAttribute('id', globalO
function addLine(lineNumberGlobal,columnnumber,insertion)
{
var newrow = document.createElement("tr");
newrow.setAttribute('id', globalObj.lineNumberGlobal);
newrow.setAttribute('onmousedown', "setCurIdG(getAttribute(\"id\"))");
for (j = 1; j <= globalObj.monthdays + 1; j++)
{
//build row cells with content
}
if (insertion == true)
{
var newrowinsert = globalObj.bodyGlobal.insertRow(globalObj.currenIdGlobal);
//this actually inserts a new empty row but I want to append my existing row "newrow"
}
else if (insertion == false)
{
globalObj.bodyGlobal.appendChild(newrow);
}
}
函数addLine(lineNumberGlobal、columnnumber、insert)
{
var newrow=document.createElement(“tr”);
setAttribute('id',globalObj.lineNumberGlobal);
setAttribute('onmousedown','setCurIdG(getAttribute(\'id'));
对于(j=1;j可以使用DOM方法。如果要在已标记的行之后插入,则需要使用该行的nextSibling
查找该行之后的行,然后在该行之前插入
如果我假设globalObj.currenIdGlobal
是您要插入的行的ID,则如下所示:
var refElement = document.getElementById(globalObj.currenIdGlobal);
if (refElement) { // Being defensive here, you probably know it _does_ exist
globalObj.bodyGlobal.insertBefore(newrow, refElement.nextSibling);
}
这假设您的HTML在行之间使用无空格或类似空格进行结构化(因为nextSibling
将返回行后的下一个节点,该节点可以是文本节点,而不是元素)。如果您需要更具防御性:
function findNextSiblingElement(elm, tagName) {
do {
elm = elm.nextSibling;
} while (elm && (elm.nodeType != 1 || elm.tagName != tagName));
return elm;
}
然后将上述内容更改为:
var refElement = document.getElementById(globalObj.currenIdGlobal);
if (refElement) { // Being defensive here, you probably know it _does_ exist
globalObj.bodyGlobal.insertBefore(newrow, findNextSiblingElement(refElement, 'TR'));
}
请注意,如果将null
作为第二个参数传递给insertBefore
,它将附加到末尾
FWIW,如果使用诸如、或之类的库,则此类操作会变得更容易。使用insertRow
创建行
另外:不要使用setAttribute
,它在IE中被破坏。事件处理程序需要函数引用而不是字符串
function addLine(lineNumberGlobal,columnnumber,insertion)
{
var newrow = globalObj.bodyGlobal.insertRow(insertion ? globalObj.currenIdGlobal : -1);
newrow.id = globalObj.lineNumberGlobal;
newrow.onmousedown = function() { setCurIdG(this.id); };
for (j = 1; j <= globalObj.monthdays + 1; j++)
{
//build row cells with content
}
}
函数addLine(lineNumberGlobal、columnnumber、insert)
{
var newrow=globalObj.bodyGlobal.insertRow(插入?globalObj.currenIdGlobal:-1);
newrow.id=globalObj.lineNumberGlobal;
newrow.onmousedown=function(){setCurIdG(this.id);};
对于(j=1;j+1,在没有所有优化的情况下写了类似的东西:-)