首页 > 解决方案 > 无法附加到节点

问题描述

我在表中有以下 html 代码:

<td id="description">
    <input id="newdescripion" value="VOIP/DATA" type="text">
    <button type="button" id="removeinput">Remove</button>
</td>

当我单击按钮时,我想清空 td 并添加存储在 cookie 中的文本。td 清空很好,但我无法附加文本。文本在变量中,因为它在警报中可见。我已经使用下面的代码来尝试实现这一点,注释掉的代码是我尝试过的并且不起作用。

$(document).on('click', '#removeinput', function() {
    var hostname =  $('#hostname').text();
    //alert(hostname);
    var trid = $(this).closest('tr').attr('id');
    //alert(trid);
    var olddesc = Cookies.get(hostname+','+trid+',description');
    alert(olddesc);
    $(this).closest('td').empty(); <----- THIS WORKS
    $(this).closest('td').append(olddesc);
    // $(this).closest('tr').find('#description').text(olddesc);
    // $(this).closest('td').text(olddesc);
    // $('#'+trid+' td').each(function(){
    //     if($(this).attr('id') == 'description'){
    //         $(this).append(olddesc);
    //     }
    // })
    //$(document).find('#'+trid+' td#description').append(olddesc);
})

任何人都可以帮我解决这个问题或推荐一种更好的方法吗?

标签: javascriptjquery

解决方案


您可以使用.html()将动态数据添加到 HTML 标记id

 var olddesc = Cookies.get(hostname+','+trid+',description');
 alert(olddesc);

 // Create custom / dynamic HTML
 var temp = `<p>` + olddesc + `</p>`;

 $(this).closest('td').empty(); <----- THIS WORKS

 // Edit: Use ID of html tag
 $('#description').html(temp);

这对你有用。


推荐阅读