JS. How to replace html element with another element/text, represented in string?

后端 未结 8 1015
清酒与你
清酒与你 2020-12-24 03:03

I have a problem with replacing html elements.

For example, here is a table:

');

    for (var i = 0; i < columns.length; i++)
        $row.append('');

    $('#__TABLE__').empty(); // remove everything inside

    $('#__TABLE__').append($row);
}

So then...

insert_columns(['hello', 'there', 'world']);

Result

0
8条回答
  •  时光取名叫无心
    2020-12-24 03:51

    Your input in this case is too ambiguous. Your code will have to know if it should just insert the text as-is or parse out some HTML tags (or otherwise wind up with bad HTML). This is unneeded complexity that you can avoid by adjusting the input you provide.

    If the garbled input is unavoidable, then without some sophisticated parsing (preferably in a separate function), you could end up with some bad HTML (like you do in your second example... which is Bad, right?).

    I'm guessing you want a function to insert columns into a 1-row table. In this case, your contents should be passed in as an array (without table, tr, td tags). Each array element will be one column.

    HTML

    JS

    using jQuery for brevity...

    function insert_columns (columns)
    {
        var $row = $('
'+columns[i]+'
hellothereworld

提交回复
热议问题