繁体   English   中英

在单击按钮上从textarea剥离html并存储剥离的文本

[英]strip html from textarea on button click and store the stripped text

  • 我尝试在单击按钮时将textarea的值加载到变量中,
  • 然后剥离所有HTML标签,但brstrong标签除外
  • 然后将新值保存到另一个变量中。

我发现此解决方案适用于普通div,但似乎不适用于textareas。 因此,我创建了一个临时div并将其html设置为textarea的值。

//Create a temporary div and initialize it with the value from the first param
var tmp         = document.createElement("DIV");
tmp.id          = "tmp";
tmp.innerHTML   = html;

这是我的尝试,不起作用。 我认为是因为我动态创建了div并且jQuery不知道它的存在?

 //init the textarea value for this example $("textarea#message").val ( "<div>\\n"+ "<strong>Hello Universe</strong>\\n"+ "<br><p>Spread good Vibes :)</p>\\n"+ "</div>" ); $("div#mybutton").on ( "click", function() { var textarea = document.getElementById("message"); var allText = textarea.value; var newText = strip_tags(allText, "strong, br"); //now do something with the new text textarea.value = newText; console.log(newText); } ); function strip_tags(html, exceptions) { console.log(html); //Create a temporary div and initialize it with the value from the first param var tmp = document.createElement("DIV"); tmp.id = "tmp"; tmp.innerHTML = html; document.body.appendChild(tmp); //Strip tags and return the whole stripped text $("#tmp *").not(exceptions).each(function(){ var content = $(this).contents(); $(this).replaceWith(content); }); } 
 div#mybutton { border: 1px solid black; width: 80px; text-align: center; } div#mybutton:hover { cursor: pointer; color: white; background-color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea> <div id="mybutton"> PRESS </div> </div> 

我找到了解决方案,有两个问题。

1.我必须将创建的DIV附加到DOM。

2.我已经在第一个周期之前回来了。

现在它可以工作了,基本上我只是从PHP函数strip_tags开发了等价的东西;)感谢karim79贡献

 //init the textarea value for this example $("textarea#message").val ( "<div>\\n"+ "<strong>Hello Universe</strong>\\n"+ "<br><p>Spread good Vibes :)</p>\\n"+ "</div>" ); $("div#mybutton").on ( "click", function() { var textarea = document.getElementById("message"); var allText = textarea.value; var newText = strip_tags(allText, "br"); //now do something with the new text textarea.value = newText; } ); //strips all html tags from a string except the tags from the whitelist, and returns the new string. (this function works exactly as the PHP equivalent strip_tags http://php.net/manual/de/function.strip-tags.php) function strip_tags(str, whitelist) { console.log("TEXT BEFORE STRIPE: (whitelist: "+whitelist+")\\n\\n"+ str); //Create a temporary div and initialize it with the value from the first param var tmp = document.createElement("DIV"); tmp.id = "tmp"; tmp.innerHTML = str; document.body.appendChild(tmp); //Strip tags and return the whole stripped text $("#tmp *").not(whitelist).each(function(){ if ($(this).is("br")) { $(this).remove(); } var content = $(this).contents(); $(this).replaceWith(content); }); var newText = tmp.innerHTML; tmp.remove(); console.log("----------------------------------------------------------"); console.log("TEXT AFTER STRIPE: (whitelist: "+whitelist+")\\n"+ newText); return newText; } 
 div#mybutton { border: 1px solid black; width: 80px; text-align: center; } div#mybutton:hover { cursor: pointer; color: white; background-color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea> <div id="mybutton"> PRESS </div> </div> 

一个完整的jQuery插件为:

 jQuery.fn.extend({ stripHtmlTags: function() { function getDivContent(input) { return $('<div></div>').html(input.val()); }; function addCheckboxes(input) { var div = getDivContent( input ); input.siblings('.tags-checkboxes').remove(); var tagsCheckboxes = $('<div class="tags-checkboxes"></div>'); var fake = getDivContent(input); var allTags = []; fake.find('*').each(function(i) { var thisTag = $(this).prop("tagName").toLowerCase(); if( $.inArray(thisTag, allTags)==-1 ) { allTags.push( thisTag ); }; }); $.each(allTags, function(t, tag) { var uniqueId = tag + '-' + Math.round(new Date().getTime() + (Math.random() * 100)); tagsCheckboxes.append('<span class="strip-tags-option"><input type="checkbox" id="' + uniqueId + '" value="' + tag + '" checked="checked" /> <label for="' + uniqueId + '">' + tag + '</label></span>'); }); input.after( tagsCheckboxes ); return tagsCheckboxes; }; function addStripButton(input) { var button = $('<button class="strip-tag-button">STRIP TAGS</button>'); input.next().after( button ); return button; } function strip(input, checkboxes) { var fake = getDivContent(input); var tagsArray = []; checkboxes.find('input').each(function(i) { var thisCheckbox = $(this); if( thisCheckbox.is(':checked') ) { tagsArray.push( thisCheckbox.val() ); }; }); var tags = tagsArray.join(', '); console.log( tags ); fake.find(tags).contents().unwrap(); fake.find(tags).remove(); input.val(fake.html()); addCheckboxes(input); }; return this.each(function() { var thisInput = $(this); if( !thisInput.hasClass('initialized') ) { var checkboxes = addCheckboxes( thisInput ); var stripButton = addStripButton( thisInput ); stripButton.on('click', function(e) { e.preventDefault(); strip(thisInput, checkboxes); }); thisInput.on('input', function(e) { checkboxes.remove(); checkboxes = addCheckboxes( thisInput ); }); thisInput.addClass('initialized'); }; }); } }); var message = $('#message'); message.val("\\ <div>\\n\\ <strong>Hello Universe</strong>\\n\\ <a href='#' title='Test'>Test link</a>\\n\\ <br><p>Spread good Vibes :)</p>\\n\\ </div>\\ "); message.stripHtmlTags(); 
 .strip-tags-option { display: inline-block; margin-right: 10px; } .strip-tag-button { border: 1px solid black; text-align: center; } .strip-tag-button:hover { cursor: pointer; color: white; background-color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea> </p> 

同样在JSFiddle上

归功于这个答案

您可以使用正则表达式

 $(function() { var html = $('textarea').val(); console.log(html.replace(/<(?!strong|br\\/?)[^>]+>/g, '')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea><strong>foo</strong><br/><div>hello</div></textarea> 

如果要在变量中包含标签,则可以使用以下代码:

 $(function() { var tags = ['strong', 'br\\\\/?']; var regex = new RegExp('<(?!'+tags.join('|')+')[^>]+>', 'g'); var html = $('textarea').val(); console.log(html.replace(regex, '')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea><strong>foo</strong><br/><div>hello</div></textarea> 

暂无
暂无

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

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