JQuery:如何将文本区域的内容选择为html字符串并从中提取文本

JQuery: How to select content of textarea as html string & extract text from it?

本文关键字:字符串 字符 html 串并 取文本 提取 选择 文本 区域 JQuery      更新时间:2023-09-26

(Failling JSfiddle on bottom)

给定JS这样:

// Fill the textarea for testing!
$("#input").val("hello <b>2</b> and <b>3</b>");
// Get the textarea, convert to html string, find b elements, get text content:
$("#input").keyup(function () {
    $('#output').html($("#input").val()).find("b").text();
}).keyup();

给定这样的 HTML :

<!-- INPUT: -->
<fieldset>
    <textarea id="input"></textarea>
</fieldset>
<!-- OUTPUT: -->
<b>List of text in b balises is:</b>
<div id="output">
    Here should be the list of n strings in b n balises (aka: ["2", "3"])
</div>

如何获取 b 元素中的 n 个字符串列表?

这目前不起作用,请参阅 JSfiddle。用JSfiddle欣赏回答。

您可以获取文本,将其作为HTML放入隐藏元素中,这会将其转换为DOM对象,然后您可以导航到该元素并提取其内容。

// Fill the textarea for testing!
$("#input").val("hello <b>2</b> and <b>3</b>");
// Get the textarea, convert to html string, find b elements, get text content:
$("#input").keyup(function () {
    var $el = $('<div>'+$("#input").val()+'</div>');
    var result = '';
    $.each($el.find('b'),function(){
        result += $(this).text()+' ';
    });
    $('#output').html(result);
}).keyup();

答案:

// Fill the textarea for testing!
$("#input").val("hello <b>2</b> and <b>3</b>");
// Get the textarea, convert to html string, find b elements, get text content:
$("#input").keyup(function () {
    $('#output').html($('#input').val());
    var list = $('#output').find("b");
    $('#output').html(""); //clean up
    list.each(function( i ) {
        $("#output").append(  "Element "+i+":" + $( this ).text() +"<br />");
    });
}).keyup();

小提琴:http://jsfiddle.net/6hCwZ/18/