繁体   English   中英

使用javascript从字符串中删除“表单”标签及其内容

[英]Remove “Form” tag with its content from string with javascript

我需要从ajax响应内容中删除表单标签。 我已经尝试过下面的代码,但是它不起作用。 任何帮助,将不胜感激。

new Ajax.Request(
  url, {
    method: "post",
    onSuccess: function (b) {
      var a = $("test");

      a.update(b.responseText.replace("[<](/)?form[^>]*[>]", ""));
  }
});

(在此答案中不使用jQuery,因为您问题中的代码显然是使用PrototypeJS代替的。)

最简单的方法是解析HTML(浏览器很乐意为您完成此操作),删除结果中的form元素,然后将其序列化回字符串(如果需要;浏览器也乐意为您完成此操作) )。

例如(不使用jQuery):

var div = document.createElement("div");
// This parses it
div.innerHTML = b.responseText;
// Find and remove the first form; tweak the selector to target if necessary
var form = div.querySelector("form");
if (form) {
    form.parentNode.removeChild(form);
}
// Convert back to string if needed
var str = div.innerHTML;

使用javascript从字符串中删除“表单”标签及其内容

假设您的意思是从string中删除“ Form”标签及其内容

如果您使用的是jquery ,则可以尝试

var $bResponseText = $( b.responseText );
$bResponseText.find( "form" ).remove();
b.responseText = $bResponseText[0].outerHTML;

在使用update功能之前

或使用jQuery的另一种方法

$("test").append( b.responseText );
$("test").find( "form" ).last().remove();

您可以简单地用<form>替换表单内容

 //detect the form, you can use id or class selector var formContent = $('form'); // replace the form with its content so that form tag is removed formContent.replaceWith(formContent.html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='content'> <form> <div>Content inside Form</div> </form> </div> 

您可以使用这样的东西:

  1. 创建一个临时div: var tempDiv = document.createElement("div");
  2. 然后将响应分配为它的innerHTML: tempDiv.innerHTML = b.responseText;
  3. 在该用户querySelectorAll之后,可以从temp div以上获取所有表单元素: var allForms = tempDiv.querySelectorAll("form");
  4. 然后遍历allForms和用户remove()方法来逐一删除表单。
  5. 之后,使用tempDiv的innerHTML获取不带表单元素的字符串: a.update(tempDiv.innerHTML);

暂无
暂无

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

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