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

时间:2016-09-09 09:56:56

标签: javascript jquery

  • 我尝试将textarea的值加载到变量按钮上 点击
  • 然后对除html标记brstrong
  • 之外的所有html标记进行条带化
  • 然后将新值保存到另一个变量中。

我发现这个solution适用于普通的div,但似乎不适用于textareas。所以我创建了一个临时div并将其设置为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);
    });
}
&#13;
div#mybutton {
  border: 1px solid black;
  width: 80px;
  text-align: center;
}

div#mybutton:hover {
  cursor: pointer;
  color: white;
  background-color: gray;
}
&#13;
<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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

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

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

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

现在它可以工作了,基本上我只是从PHP函数 strip_tags 开发了等效项;)为 karim79 的积分为他的{{ 3}}。

&#13;
&#13;
//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;
}
&#13;
div#mybutton {
  border: 1px solid black;
  width: 80px;
  text-align: center;
}

div#mybutton:hover {
  cursor: pointer;
  color: white;
  background-color: gray;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

this answer的信用。

答案 2 :(得分:0)

您可以使用正则表达式

&#13;
&#13;
$(function() {
  var html = $('textarea').val();
  console.log(html.replace(/<(?!strong|br\/?)[^>]+>/g, ''));
});
&#13;
<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>
&#13;
&#13;
&#13;

如果您想在变量中添加标签,可以使用以下代码:

&#13;
&#13;
$(function() {
  var tags = ['strong', 'br\\/?'];
  var regex = new RegExp('<(?!'+tags.join('|')+')[^>]+>', 'g');
  var html = $('textarea').val();
  console.log(html.replace(regex, ''));
});
&#13;
<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>
&#13;
&#13;
&#13;