使用 java 脚本函数重新加载 HTML 元素

Reload an HTML element using a java script function?

本文关键字:加载 HTML 元素 新加载 java 脚本 函数 使用      更新时间:2023-09-26

好吧,我有点问一个由两部分组成的问题,但回答任何一部分都会帮助我。我将直接回答我的问题,并直接跳到我需要帮助的地方。我正在尝试使用 Javascript 函数来定义 iframe 的某些元素,以便用户可以决定源、高度和宽度。我现在拥有的代码如下所示。

<script language="javascript">
window.onload = webPage;
	function webPage(){
	var page = prompt("please enter the website","www.google.com");
	var height = prompt("Please enter the height of the frame","800");
	var width = prompt("Please enter the width of the frame","600");
}
</script>
<iframe src=page height=height width=width>
</iframe>

有没有办法重新加载 iFrame 并让它使用用户输入作为我当前代码的元素?我还需要做其他事情才能将变量用于 iFrame 吗?感谢任何看我的问题并期待您的回答的人。

首先使用空白值和一个唯一 ID 初始化 IFrame,然后追加用户输入。

这是工作JSFiddle Link

动态更改值:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
</head>
<body>
<iframe id="icereaper666" src="" height="0" width="0"></iframe>
<script language="javascript">
window.onload = webPage;
function webPage(){
    var page = prompt("please enter the website","http://www.w3schools.com/");
    var height = prompt("Please enter the height of the frame","400");
    var width = prompt("Please enter the width of the frame","400");
    var iframeElement = document.getElementById("icereaper666");
    iframeElement.src = page;
    iframeElement.height = height;
    iframeElement.width = width;
}
</script>
</body>
</html> 

注意:您还可以使用 createElement 动态创建 IFrame 元素。 Check this out

使用创建元素:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
</head>
<body>
<script language="javascript">
    window.onload = webPage;
    function webPage(){
        var page = prompt("please enter the website","http://www.w3schools.com/");
        var height = prompt("Please enter the height of the frame","400");
        var width = prompt("Please enter the width of the frame","400");
        var iframeElement = document.createElement("iframe");
        iframeElement.src = page;
        iframeElement.height = height;
        iframeElement.width = width;
        document.body.appendChild(iframeElement);
    }
</script>
</body>
</html>

<script language="javascript">
window.onload = webPage;
	function webPage(){
	var page = prompt("please enter the website","www.google.com");
	var height = prompt("Please enter the height of the frame","800");
	var width = prompt("Please enter the width of the frame","600");
//new content here
document.getElementById("theIframe").innerHTML="<iframe src='""+page+"'" height='""+height+"'" width='""+width+"'"></iframe>";
}
</script>
<div id="theIframe"></div>