1

如何删除动态生成的 div 的 lastchild 并将 html 重新生成为字符串。示例 HTML DIV

strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
    <div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
    <div id='multiselectAnchors' type='multi'>
        <div id='options32' >Two</div>
        <div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
    </div>
    <div id='blank4' contenteditable='true' type='blankField'>&nbsp;&nbsp;&nbsp;</div>
    <div id='Div1' type='multi'>
        <div id='options33' >Three</div>
        <div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
    </div>"

这是代码示例

if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {

strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work) 

}

需要在运行时删除 div 的 lastchild 并像以前一样转换回字符串。我可以进行字符串操作,但可能不是正确的方法,请建议

4

3 回答 3

2
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();

var str = el.wrap("<div/>").parent().html()
于 2013-08-29T14:09:57.480 回答
1

动态生成 DIV:

$('body').append('<div>');

生成后立即访问 DIV:

var $divElement = $('body').append('<div>').find('div');

获取最后一个孩子:

var $lastChildElement = $divElement.last();

获取最后一个孩子的 HTML(更具体地说,是innerHTML):

var $lastChildHTML = $lastChildElement.html();

一起做,然后转身:

var $lastChildHTML = $('body').append('<div>').find('div').last().html();

那就是关于它的一切。

于 2013-08-29T14:06:56.607 回答
1
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();
于 2013-08-29T14:07:08.463 回答