从文本区域中剥离html按钮点击并存储剥离的文本

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

本文关键字:剥离 文本 存储 html 区域 按钮      更新时间:2023-09-26
  • 我试图将文本区域的值加载到按钮上的变量中单击
  • 则将除html标签brstrong之外的所有html标签分条
  • 然后将新值保存到另一个变量中

我发现了这个解决方案,它适用于普通div,但似乎不适用于文本区域。因此,我创建了一个临时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>

一个完整的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上。

归功于这个答案。

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

1.我不得不将创建的DIV附加到DOM中。

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

现在它工作了,基本上我只是从PHP函数strip_tags中开发了equivalent;(感谢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>

您可以将regex用于

$(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>