繁体   English   中英

如何通过单击按钮在页面中包含html文件?

[英]How can I include an html file in my page by clicking on a button ?

我试图获得一个带有简单按钮的页面,该按钮将在单击时加载另一个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;
}

每次我单击按钮时,都会出现另一个正方形。 使用javascript或jquery,ajax或anyting怎么可能?

谢谢

与其产生另一个HTTP调用,而且不必去获取总是相同的文件内容的复杂性,不如仅单击按钮就生成一个正方形,会更好。

通过为所有新的div赋予自己的CSS类,您可以为所有样式设置相同的样式,而无需保留所有原始div。

为了清楚起见,在我的示例中,我向每个新方块添加了相同的内容,但是如果要向click事件处理程序中添加条件逻辑,则可以根据自己的逻辑在不同的方块中创建不同的内容。

如果要添加的内容只是纯文本,则使用textContent属性将内容注入正方形;如果要注入需要解析的内容,则使用innerHTML属性(即,您的内容包含标记-例如,当我添加文本“ 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> 

您可以使用<iframes>在页面上加载另一个网页。 您可以使用Javascript不断在彼此之间添加页面的<iframes> ,从而创建所需的效果。 W3Schools上有一篇有关如何使用<iframes>的文章。

编辑:请注意,绝对不是执行手头任务的最佳方法。 使用CSS和Javascript可以实现相同的效果,而无需加载多个网页。

暂无
暂无

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

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