更新两个HTML文件在使用同一时间的javascript(Update two html files

2019-10-21 18:09发布

我是很新的这些话题,所以它可能是一个简单的问题,但我无法通过在google回答。

我有两个HTML文件和JavaScript文件(见下文)。 所述第一HTML文件中包含的输入字段,其中一个用户可以输入在摄氏度的温度。 然后,该数字转换为使用被称为“convTemp” JavaScript函数开尔文温度。

问题是输出。 我想获得打印在两个HTML页面的结果(“<P ID =”输出“>文本将被替换</ P>”),但目前它仅适用于其中的一个文件。 我怎样才能修改JavaScript文件/ HTML文件进行更新,同时这两个HTML文件,而不是只有一个? 任何意见,欢迎! 如果使用JavaScript是不可能的,怎么回事能不能做到?

下面是我使用演示使用一个小玩具例子问题的文件:

HTML文件号1:

<html>
<head>
<title>JavaScript-Test</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
<form name="Calc">
<input type="text" name="myNumber" size="3">
<input type="button" value="convert temperatures" onclick="convTemp(document.Calc.myNumber.value, 'output')"><BR>
<p id="output">Here the output will appear and a new tab will open as well.</p>
</body>
</html>

HTML文件号2:

<html>
<head>
<title>HTML number 2</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
<p id="output">This replacement does not work yet</p>
</body>
</html>

JavaScript文件:

 function convTemp(x, tID) {
     var res = parseFloat(x) + 273.15;
     window.open('htmlfile2.html'); /*, "_self" */
     document.getElementById(tID).innerHTML = x + " degrees are " + res + " Kelvin.";
}

编辑:我试过localStorage的解决方案,但它仍然无法正常工作。 JS文件现在如下所示:

function convTemp(x) {

   var res = parseFloat(x) + 273.15;
   /*window.open('htmlfile2.html'); /*, "_self" */


   if (typeof(Storage) != "undefined") {
        localStorage.setItem("resCalc", res);
        window.location.href = 'htmlfile2.html';
        document.getElementById("output").innerHTML = x + " degrees are  "     + localStorage.getItem("resCalc") + " Kelvin.";
    }
    else {
    document.getElementById("output").innerHTML = "Sorry, your browser does not support Web Storage...";
    }   
}

有任何想法吗? 谢谢!

编辑2:我添加了一个工作液(见下文)。 如果任何人有更好的解决方案,请发表它 - 感谢!

Answer 1:

By using localStorage - as suggested by epascarello and Michael - I could solve the problem although I doubt that it is the most aesthetic one.

Here are the files, maybe someone else runs into this problem or can suggest a better solution later on:

htmlFile1.html:

<html>
<head>
<title>JavaScript-Test</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
  <form name="Calc">
     <input type="text" name="myNumber" size="3">
     <input type="button" value="convert temperatures"    onclick="convTemp(document.Calc.myNumber.value)"><BR>
  <div id="output">Here the output will appear and a new tab will open as well.</div>
</html>

htmlfile.2.html:

<html>
<head>
<title>HTML number 2</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
    <div id="output">This replacement does work now.</div>
    <script>showData();</script>
</body>
</html>

And the js file JSfunc.js:

function convTemp(x) {

   var res = parseFloat(x) + 273.15;

   if (typeof(Storage) != "undefined") {
        //localStorage.setItem("resCalc", resString);
        setData("resCalc", res.toString());
        setData("origVal", x);
        showData();
        window.open('htmlfile2.html'); //, "_self" 
    }
    else {
    document.getElementById("output").innerHTML = "Sorry, your browser does not support Web Storage...";
    }

}

function setData(tfield, tval)
{
    localStorage.setItem(tfield, tval);
}

function showData()
{
    var tstr = localStorage.getItem("resCalc");
    var x = localStorage.getItem("origVal");

    document.getElementById("output").innerHTML = x + " degrees are " + tstr + " Kelvin.";  
}

Comments/improvements are always welcome!



Answer 2:

我认为你需要postMessage做到这一点。 您可以将消息发送到另一个窗口,让您可以同时更新。

也许:

var otherwindow = window.open("htmlfile2.html");
otherwindow.postMessage({ x: x, res: res }, "*");

而在HTML文件号2:

window.addEventListener("message", function (ev) {
  // Update your HTML using ev.data
});


Answer 3:

你只能改变与JavaScript的当前DOM,但你可以使用如饼干改变那些在一个页面上后能得到这两个网页上显示的数据。 优选的是,如果你使用PHP或任何服务器端语言太,要走的路是保存的条目在数据库中,并从那里拉他们。

这里是取自功能这个答案创建和检索cookie。

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

用法:

设置Cookie:

<html>
<head>
<title>JavaScript-Test</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
<form name="Calc">
<input type="text" name="myNumber" id="myNumber" size="3">
<input type="button" value="convert temperatures" onclick="convTemp(document.Calc.myNumber.value, 'output')"><BR>
<p id="output">Here the output will appear and a new tab will open as well.</p>
</body>
</html>

JSFunc.js:

document.onload = function(){
document.getElementById('myNumber').addEventListener('keyup', addtoCookie);
function addtoCookie() {
var inputs = document.getElementById('myNumber').value

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
createCookie('entry',inputs,30);
}
}

然后,您可以加载页面加载cookie的内容:

<html>
<head>
<title>JavaScript-Test Page2</title>
<script src="JSfunc2.js" type="text/javascript"></script>
</head>
<body>

<p id="output">Here the output will appear and a new tab will open as well.</p>
</body>
</html>

JSFunc2.js(让我们说的cookie被称为“入口”):

document.onload=function() {
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

 document.getElementById('output').innerHTML = getCookie('entry');

}


Answer 4:

发送的查询字符串

window.open('htmlfile2.html?temp=' + encodeURIComponent(res));

阅读下页

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var temp = getParameterByName('temp');
console.log(temp);


文章来源: Update two html files at the same time using javascript