简体   繁体   English

jQuery:在文本区域内添加到段落的html的最佳方法

[英]jQuery: Best way to append to html of a paragraph inside a textarea

I have a textarea that contains variable html content which is always wrapped in a paragraph (p) tag. 我有一个textarea,其中包含可变html内容,该内容始终包装在(p)段标记中。

HTML (before appending): HTML(附加之前):

<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content.</p></textarea>

I fetch this content using the following in jQuery: 我在jQuery中使用以下内容获取此内容:

jQuery: jQuery的:

$('#comments').val();

Now I need to append HTML at the end of this paragraph but inside the p tag. 现在,我需要在本段末尾的p标记内附加HTML。

HTML (after appending): HTML(添加后):

<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content. Some appended HTML.</p></textarea>

I can of course replace the last 4 characters of the above (which is the closing p tag), then append my HTML and then add the closing p tag again. 我当然可以替换上面的最后4个字符(即p结束标记),然后附加我的HTML,然后再次添加p结束标记。 Can someone tell me if there is a better way to achieve the same in jQuery ? 有人可以告诉我在jQuery中是否有更好的方法可以实现相同目的?

Many thanks in advance for this, Tim. 蒂姆,在此先感谢您。

Parse the string value of the textarea as HTML, and insert whatever you like, then pass the string value of the HTML back 将textarea的字符串值解析为HTML,然后插入任意内容,然后将HTML的字符串值传递回

$('#comments').val(function(_, val) {
    return $('<div />', {html:val}).find('p').append('content').end().html();
});

FIDDLE 小提琴

This could do the trick 这可以解决问题

var html = $('#comments').val();
$('#comments').val(
    $(html).append('  Some appended HTML.')[0].outerHTML
);

DEMO 演示

Ok. 好。 I REALLY love this! 我真的很喜欢这个!

$('#comments').text($($('#comments').text()).append(' a new insert!').text());

Don't look at it too long. 不要看太久。 Could hurt your eyes :-) 可能会伤害您的眼睛:-)

You could insert the value into a temporary div, add an element to the <p> -element inside the temporary div and fetch the renewed content again: 您可以将值插入临时div,在临时div内的<p> -element中添加元素,然后再次获取更新的内容:

var tmpDiv = $('<div></div>'); //create temporary element
tmpDiv.html($('#comments').val()); // add HTML from textarea
$(someHtml).appendTo($('p', tmpDiv)); // append custom HTML to P inside temp element
newTextAreaValue = tmpDiv.html(); // retrieve new value

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

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