如何导入 html 并插入 div?

How to import html and insert onto a div?

我想将一个 html 文件插入另一个 div 的 html 文件中。我不精通javascript,所以想到了这个主意。

<head>
    <link rel="import" href="polymer/polymer.html" />
    <link rel="import" id="note-import-01" href="some.html" />
</head>
<body>
<div id="notes">
    <div id="blocker"></div>
    <script type="text/javascript">
        var link = document.querySelector('#note-import-01');
        var content = link.importNode;
        parent.insertBefore(content);
    </script>
</div>
</body>

然而,它并没有出现我想要的。例如,带有 id 拦截器的 div 不包括页面内容。 抱歉,这里我指的是第 3 行的 some.html。

注意

将 jQuery 添加到页面,然后用适当的 URL 代替示例。

<script type="text/javascript">
   jQuery(document).ready(function(){
       jQuery("#blocker").load("yourURLHere");
   });
</script>

您可以使用 jquery 的 load

$("#blocker").load("polymer/polymer.html");

或使用普通 javascript

var xhr= new XMLHttpRequest();
xhr.open('GET', 'polymer/polymer.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState==4 && this.status==200)                
        document.getElementById('blocker').innerHTML= this.responseText;
};
xhr.send();

您可以尝试使用 jQuery .load() 方法将 html 文件 some.html 加载到当前页面。

下面的解决方案有一个锚标记 a,它有一个 click 事件处理程序,在处理程序内部加载了本地 html 页面 some.html

JS代码:

$(document).ready(function(){
      $('#aUrl').hide();
      $('#divPage').load(this.href); 
 });

HTML代码:

<div id="divPage"></div>
  <a href="http://lesson8.blogspot.in/2012/06/bind-gridview-using-jquery.html" id="aUrl">Load Page</a>

现场演示@JSFiddle:http://jsfiddle.net/dreamweiver/dVPQw/740/

注意:上面的jsfiddle不允许加载远程资源,但在你的情况下,本地资源将被完美加载

您可以像这样使用 HTMLImports 执行此操作:

<pre id="notes"></pre>

<script>
  function importLoaded(link, slctr) {
    document.querySelector(slctr).appendChild(link.import.body);
  }
</script>

<link href="polymer/bower.json" rel="import" onload="importLoaded(this, '#notes')">