表中有以下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);
})有人能帮我解决这个问题或者推荐一个更好的方法吗?
发布于 2018-09-05 21:10:11
$(this).closest('td').append(olddesc);在您从td中删除this之后运行,因此td不再是this的祖先。您不需要清空td;只需将其文本设置为olddesc,它将作为设置文本过程的一部分自动清空。
// (REMOVE THIS) $(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').text(olddesc);发布于 2018-09-05 20:54:03
您可以使用.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);这对你来说是可行的。
发布于 2018-09-05 21:19:04
只需使用.html
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
var olddesc = "Cokkies return"; //Cookies.get(hostname+','+trid+',description');
$(this).closest('td').html(olddesc); //<----- THIS WORKS
}) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
</tr>
</table>
https://stackoverflow.com/questions/52193187
复制相似问题