简体   繁体   English

替换元素而不是追加

[英]replace the element instead of append

I have the following code where i need to replace the newly created TD column with the new option from the dropdown select. 我有以下代码,我需要使用下拉菜单中的新选项替换新创建的TD列。 Here is my code 这是我的代码

$("#myselction").change(function(e) {
    var neData = $("#myselction").val();
    $("table.data thead tr").append("<th>Idea</th>");
    $("table.data tr:gt(0)").append("<td>" + neData + "</td>");
});

It is appending the data correctly at the end of the table, but everytime i select new option from dropdown, it adds another td column, instead i want to replace it with the one already created and if its new one create it first time. 它在表的末尾正确地附加了数据,但是每次我从下拉列表中选择新选项时,它都会添加另一个td列,而我想将其替换为已创建的td列,如果它的新列是第一次创建它。

Alo i am using the following function to add/remove class for odd and even 我正在使用以下功能为奇数和偶数添加/删除类

    zebRaRows('.data tbody tr:odd td', 'odd');
function zebRaRows(selector, className){
  $(selector).removeClass(className).addClass(className);
}

How do i add the above to the dynamically created column 如何将以上内容添加到动态创建的列中

you need to replace append() which append with html() which replace. 您需要将append()替换为替换的html()

try: 尝试:

$("selector of element to replace").html("<td>" + neData + "</td>");

Here is fiddler for html demo 这是HTML演示的提琴手

Your desired behavior is different depending on whether it is the first time the action is occurring or not. 您期望的行为会有所不同,具体取决于是否是第一次执行操作。 In this case, have a boolean flag which records the first time the event occurs. 在这种情况下,请具有一个布尔标志,该标志记录事件的第一次发生。 The first time, append the new <td> ; 第一次,添加新的<td> subsequent times, overwrite it. 随后的时间,将其覆盖。

jsFiddle jsFiddle

var firstTime = true;

$("#myselction").change(function(e) {
    var neData = $("#myselction").val();

    if (firstTime) {
        $("table.data thead tr").append("<th>Idea</th>");
        $("table.data tr:gt(0)").append("<td>" + neData + "</td>");
        firstTime = false;
    }
    else {
        $("table.data tr:gt(0) td:last-child").html(neData);
    }
});

使用.html()创建一个新的。

$("table.data tr:gt(0)").html("<td>" + neData + "</td>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM