【问题标题】:preview of text using jquery使用 jquery 预览文本
【发布时间】:2011-09-26 12:51:41
【问题描述】:

我有以下html

<img src="a.jpg" /><p> This is some random text and just to test this example. This is some random text and just to test this example. This is some random text and just to test this example<p> <br><p>This is some random text and just to test this example This is some random text and just to test this example</p> <img src="a.jpg" /> <br><p>This is some random text and just to test this example This is some random text and just to test this example</p>

我的问题是,如果我必须只使用 jquery 来预览文本,假设我在一个名为 html 的变量中有这个,如何只显示文本的几个部分而忽略图像

       <div id="preview"></div>
       $("#preview").val("//display only text in the variable named html") 

【问题讨论】:

  • hi rajeev .. 好名字你有:-) 你的问题不太清楚。我认为您希望通过从 html div 获取另一个 div 的价值。我对吗 ?然后使用这个 $("#preview").html("//只显示名为 html 的变量中的文本")

标签: javascript jquery jquery-selectors jquery-validate


【解决方案1】:
$('#preview').html(textWithTags.replace(/(<([^>]+)>)/ig,"").substr(0, 200));

注意:DIV 使用.text().html() 而不是.val()

【讨论】:

    【解决方案2】:

    试试这个:

    Here `.content` is class of wrapper of whole html you post
    

    代码:

    $('.preview').click(function(){ // Here `.preview` is the `class` of submit button
        html = $('.content').contents(':not(img)');
        $('#preview').html(html)
    });
    

    $('#preview').html($(yourhtml).not('img'));
    

    html = $('.content').html();
    yourhtml = $(html).contents(":not('img')").text().substr(0, 200).concat('...'); // here  I add `concat('...')` just for continuity. you may remove it,
    $('#preview').html(yourhtml);
    

    【讨论】:

    • 在这里我用div 包装你的html 类content
    • @Rajeev 前两个解决方案会将整个 html 设置为 #preview,但最后一个解决方案会将 text 设置为 #preview
    【解决方案3】:

    你可以filter来自html的图片:

    var someHtml = '....';
    $('#preview').html($(someHtml).filter(':not("img")'));
    

    【讨论】:

    • @Rajeev,这里有很多段落。您希望将哪一个限制为 200 个字符?
    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2012-06-25
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多