【问题标题】:Manipulate html String before inserting into DOM在插入 DOM 之前操作 html 字符串
【发布时间】:2016-09-14 15:33:30
【问题描述】:

我有一个 htmlString。我正在将该字符串放入 iframe 中。 代码是

var iframe = document.createElement('iframe'); 
var html = '<html> <head></head> <body> //contents </body> </html>';

document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

现在我要做的是插入一个标签

<base href="some url" >

进入 htmlString 的头部。然后我想将 iframe 附加到 dom 并将 htmlString 写入该 iframe。

如何在将 htmlString 插入 iframe 之前对其进行操作?

【问题讨论】:

    标签: javascript jquery html dom iframe


    【解决方案1】:

    给你:https://jsfiddle.net/tjcwyem6/

    我使用了以下 JavaScript:

    var iframe = document.createElement('iframe'),
        html = '<html> <head></head> <body> //contents </body> </html>',
        newurl = "https://www.facebook.com/",
        basehref = "<base href='" + newurl + "'>",
        n = html.indexOf("</head>");
    
    var newhtml = [html.slice(0, n), basehref, html.slice(n)].join('');
    
    document.body.appendChild(iframe);
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(newhtml);
    iframe.contentWindow.document.close();
    
    console.log(newhtml);
    

    我的修改如下:

    1. 将您的 url 值存储在 newurl 中。
    2. 将其放入字符串basehref
    3. 获取 HTML 字符串中&lt;/head&gt; 所在的位置。
    4. 通过切片和连接字符串将basehref 添加到newhtml

    【讨论】:

      【解决方案2】:

      您可以使用 jquery 来附加 iframe 内容,例如 -

      $("iframe").contents().find("head").append('<base href="some url" >');
      

      【讨论】:

      • 虽然这样更干净更自然,但它不会在将字符串插入 iframe 之前对其进行操作。
      【解决方案3】:

      您可以通过将其作为 XML 加载到 jquery 中并使用 jquery 来操作来操作 html:

      var xml = $.parseXML("<html> <head></head> <body> //contents </body> </html>");    
      $("head", xml).append("<base url='x'/>")
      
      var html;
      if (window.ActiveXObject) {
          html = xml.xml;
      } else {
          html = (new XMLSerializer()).serializeToString(xml);
      }
      
      iframe.contentWindow.document.write(html);
      

      This answer 用于 xml 到 html 的详细信息

      您不能将 html 作为 html 加载到 jquery 中,因为它会剥离 body/head。

      【讨论】:

        【解决方案4】:
        String.prototype.insertAt=function(index, string) { 
                return this.substr(0, index) + string + this.substr(index);
        }
        var myhtml = "<html> <head></head> <body></body> </html>";
        var m = myhtml.indexOf("</head>");
        myhtml = myhtml.insertAt(m, '<base href="some url" >');
        console.log(myhtml);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 2018-01-04
          相关资源
          最近更新 更多