jQuery text()函数在IE中丢失换行符 [英] jQuery text() function loses line breaks in IE

查看:155
本文介绍了jQuery text()函数在IE中丢失换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery论坛上这是一个非常讨论的问题,但我无法找到适合我情况的解决方案。

This is quite a talked about problem on the jQuery forums but I can't figure out a solution for my situation.

我有一个带有一些文本的无序列表其中的元素......用户可以通过jQuery创建新的列表项,这些项目保存到SQL数据库中。他们还可以编辑现有的列表项。此外,由于每个列表项中的文本可能会很长,因此可以选择隐藏每个列表项,以便显示字符串的截断版本。这是由一个自定义的jQuery插件处理的,该插件截断了超过一定长度的列表项...这就是截断插件格式化后每个列表项的样子:

I have an unordered list with some text elements in them... the user can create new list items via jQuery, which are saved to an SQL database. They can also edit existing list items. Also, because the text in each list item can get quite long, they have the option of 'hiding' each list item so it shows a truncated version of the string. This is handled by a custom jQuery plugin that truncates list items that are over a certain length... here's what each list item looks like once the truncate plugin has formatted it:

<li id="item_1">
<div class="note">
    This is the text that shows when this element is truncated <span style="display: none;" class="truncate_ellipsis">...</span>
<span style="display: inline;" class="truncate_more">This is the text that will be hidden if the user clicks on the 'hide' button</span>
</div>  
<div class="toggle_wrapper"> 
    <div class="note_toggle">
        <a href="#" class="truncate_more_link">Hide note</a>
    </div> 
    <div style="display: block;" class="note_controls"> 
        <span class="edit_note"><a href="#note_textfield" id="edit_note_1">Edit</a></span> | <span class="delete_note"><a href="#" id="delete_note_1">Delete</a></span> 
    </div> 
</div> 
</li>

我遇到的问题是用户点击编辑并获取div的内容使用班级'note'并将其分配到文本区域。然后,用户可以编辑文本并保存。我使用以下脚本来获取div的内容并将其分配给textarea:

The problem I have is that the user clicks on 'edit' and it takes the contents of the div with the class 'note' and assigns it to a text area. The user can then edit the text, and save it. I am using the following script to grab the contents of the div and assign it to the textarea:

$('.edit_note a').click(function(event){

    // Get the parent li of the 'edit' link that was clicked 
    var parentLi = $(this).closest('li');

    // fade out the li that's being edited
    parentLi.fadeOut('fast');

    // remove the '...' that shows when the note is truncated
    parentLi.find('.truncate_ellipsis').remove();

    // find the 'note' div within the li that's being edited
    var currentNote = parentLi.find('.note');

    // grab the id of this note... used when saving to the DB
    var noteId = $(this).attr('id').substr(10);

    // Set the current note id variable and editing status
    currentNoteId = noteId;
    currentNoteStatus = 'edit';

    //add the note ID as a hidden field to the text editor form
    $('input[name$="note_id"]').val(noteId);

    // grab the text from this note and add it to the text area
    // (textarea id is 'notes_content')
    $('#notes_content').val($.trim(currentNote.text()); // this is the text area

    // fade in the text area so the user can edit
    $('div.notes_textarea').fadeIn();

});

一旦保存,我正在使用我在网上发现的功能,将换行符转换为BR,之前将文本区域的内容分配回相应列表项中的notediv:

Once it's saved I'm using a function I found online to convert the line breaks to BRs, before assigning the contents of the text area back to the 'note' div within the appropriate list item:

function nl2br (str, is_xhtml) {   
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

这一切在firefox / chrome / opera / safari中运行良好...但是IE通过jQuery text()函数抓取文本时摆脱了换行符。这个在jQuery文档的本页评论中讨论过:

This all works fine in firefox / chrome / opera / safari... however, IE gets rid of the line breaks when it grabs the text via the jQuery text() function. This is discussed in the comments of this page on the jQuery documentation:

http://api.jquery.com/text/

有些人通过克隆源元素取得了成功,将其包装在'pre'中'标记,然后获取其内容并将其放入文本区域。这适用于换行符,但也带来了额外的空格,标签等等,看起来有点混乱。一个更好的解决方案似乎是使用html()jQuery函数来获取文本,然后替换br用于换行符,并删除任何其他html格式。

Some people have had success by cloning the source element, wrapping it in 'pre' tags, then taking the contents of that and putting it in the text area. This works for line breaks but also brings over extra spaces, tabs etc. and it looks a bit of a mess. A better solution seems to be to use the html() jQuery function to grab the text, then replace br's for line breaks, and strip out any other html formatting.

I然而,我是Javascript的新手,而且我对正则表达式很垃圾,所以我不知道如何做到这一点,而且我已经没时间了!我需要一个正则表达式,或者只需要一些字符串格式化帮助来执行以下操作:

I'm new to Javascript however, and I'm rubbish at regular expressions so I wouldn't have a clue how to do this and I'm running out of time! I need a regular expression, or just some help with string formatting to do the following:


  • 从字符串中删除所有span标记没有删除跨度的内容(我的截断函数添加了一个带有truncate_more类的跨度...请参阅上面的html代码)

  • remove all span tags from a string WITHOUT removing the contents of the span (my truncate function adds a span with the class "truncate_more" ... see html code above)

删除br和替换它们的换行符会在textarea元素中正确显示并在浏览器中保持一致

remove br's and replace them with newline characters that will display correctly in a textarea element and be consistent across browsers

或者..如果有人知道的话对于这个IE / textarea / linebreak问题的一个更好的解决方法,我真的很感激白痴指南:)

OR.. if anyone knows of a better workaround to this IE / textarea / linebreak issue, I'd really appreciate an idiots guide :)

很多信息可能是一个简单的解决方案但我想我会尽力解释这种情况!任何帮助都会非常感激....

Quite a bit of information for what is probably a simple solution but I thought I'd try to explain the situation as best I could! Any help would be hugely appreciated....

编辑:'TheJuice的答案在下面适用于br / IE换行问题(谢谢! ),但我需要执行类似的正则表达式来摆脱跨度,因为它们只封装了一些文本。我尝试了以下,这似乎在Firefox中工作正常,但在IE中,跨度仍然存在:

EDIT: 'TheJuice's answer below worked for the br's / IE line breaks issue (thanks!), but I need to carry out a similar regex to get rid of the spans, as they only encapsulate some of the text. I tried the following, which seems to work fine in firefox but in IE the spans remain:

        var withBRs = currentNote.html();
    var textWithBreaks = withBRs.replace(/\<br\>/gi,'\r');
    textWithBreaks = textWithBreaks.replace(/\<.*span.*\>/g, '');

另一个编辑:'TheJuice'也解决了这个问题...忽略我可怕的正则表达式,如果你发现自己处于同样的境地,就去做他说的话!感谢所有提出建议的人......

ANOTHER EDIT : 'TheJuice' solved this problem too... ignore my horrific regex and just do what he says if you find yourself in the same situation! Thanks to all who offered suggestions...

推荐答案

这是一个更简单的解决方案,可以将任何HTML转换为带有换行符的纯文本基于< br> < p> 标签的使用。

Here is a far simpler solution to convert any HTML into plain text with line breaks based on the use of <br> or <p> tags.

function htmlDecodeWithLineBreaks(html) {
  var breakToken = '_______break_______',
      lineBreakedHtml = html.replace(/<br\s?\/?>/gi, breakToken).replace(/<p\.*?>(.*?)<\/p>/gi, breakToken + '$1' + breakToken);
  return $('<div>').html(lineBreakedHtml).text().replace(new RegExp(breakToken, 'g'), '\n');
}

例如,调用以下方法:

htmlDecodeWithLineBreaks('line 1<br>line &amp; 2<br />' + 
  'line &gt; 3<p>paragraph 1</p>line 4')

返回:

line 1
line & 2
line > 3
paragraph 1
line 4

希望有所帮助;)

这篇关于jQuery text()函数在IE中丢失换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆