javascript - 如何通过单击按钮将 html 文件包含在我的页面中?

标签 javascript html button include

我正在尝试获取一个带有简单按钮的页面,该按钮将在单击时加载另一个 html 页面的内容。

<input type="button" value="Create a square" id="send" onClick="createaquare()" />

我想要的是,当我单击按钮时,该函数会创建一个名为的正方形,加载另一个包含简单正方形的 html 文件。

    <div></div>

<style type="text/css">

div
{
    height : 200px;
    width : 200px;
    background: red;
    opacity : 0.3;
}

每次我单击该按钮时,都会出现另一个方 block 。使用 javascript 或 jquery、ajax 或任何其他方法怎么可能实现这一点?

谢谢

最佳答案

与其引发另一个 HTTP 调用和必须获取始终相同的文件内容的复杂性,不如在按钮单击时生成方 block 要好得多。

通过为所有新 div 提供自己的 CSS 类,您可以将它们设置为相同的样式,同时保留所有原始 div。

需要明确的是,在我的示例中,我向每个新方 block 添加相同的内容,但是如果您要向单击事件处理程序添加条件逻辑,则可以根据自己的逻辑在不同的方 block 中创建不同的内容。

使用textContent将内容注入(inject)到方 block 中属性,如果它只是您想要添加的直接文本,请使用 innerHTML属性,如果您想注入(inject)需要解析的内容(即您的内容包含标记 - 例如,当我将文本“ESPN”添加到链接时,我还会添加一个 HTML <br> 元素)。

var btn = document.getElementById("btnMakeSquare");

var counter = 1;

btn.addEventListener("click", function(){

  // Create a new square and configure it:
  var newSquare = document.createElement("div");
  newSquare.id = "newDiv" + counter;
  newSquare.textContent = newSquare.id;
  newSquare.setAttribute("class", "newDiv");
  
  // Now create content for that square (this can be anything)
  var newLink = document.createElement("a");
  newLink.href = "http://espn.com";
  newLink.innerHTML = "<br>ESPN";
  newLink.id = "link" + counter;
  
  // Put the link into the square:
  newSquare.appendChild(newLink);
  
  // Bump up the counter:
  counter++;
  
  // Inject the square (which now contains a link) into the DOM:
  document.body.appendChild(newSquare);
  

});
/* Only the one original div will be affected by this: */
#originalDiv {
    height : 50px;
    width : 50px;
    background: red;
    opacity : 0.3;

}

/* All generated divs will have the following class 
   so they will all look the same. But, none of the
   original divs will have this class, so they won't
   be affected.                                      */
.newDiv {
    height : 75px;
    width : 75px;
    background: blue;
    border:1px solid black;
    font-weight:bold;
    font-size:.1.5em;
    color:yellow;
    text-align:center;
}

/* This only affects links in new squares */
.newDiv > a{
  color:green;

}
<input type="button" value="Create a square" id="btnMakeSquare">
<div id="originalDiv">I'm the original div</div>

关于javascript - 如何通过单击按钮将 html 文件包含在我的页面中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091023/

相关文章:

javascript - Jquery UI - 在点击的div上动态绑定(bind)按键事件

c# - Visual Studio 中列表框的上移、下移按钮

jquery - 具有不同 id 的多个按钮的一种功能

javascript - 获取另一个元素内 anchor 的 'href' 值

javascript - jQuery - 日期选择器未填充 HashMap 日期字段

javascript - 为等效的其他 ID 添加类

java - 使用 jsoup 将相对链接转换为绝对链接

android - 如何使用按钮在 TextView 中设置文本并更改屏幕?

javascript - 如何在 Android 股票浏览器的只读输入字段上显示省略号?

javascript - 为什么动画结束后元素的宽度会发生变化?