使用javascript同时更新两个html文件

时间:2015-01-30 14:10:05

标签: javascript jquery html local-storage session-storage

我对这个话题很新,所以这可能是一个简单的问题,但我无法通过谷歌搜索来回答。

我有两个HTML文件和一个javascript文件(见下文)。第一个HTML文件包含一个输入字段,用户可以在该字段中输入以度为单位的温度。然后使用名为“convTemp”的javascript函数将此数字转换为开尔文温度。

问题是输出。我想在两个HTML页面上打印结果(在“< p id =”output“>要替换的文本< / 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:我添加了一个有效的解决方案(见下文)。如果有人有更好的解决方案,请发布 - 谢谢!

4 个答案:

答案 0 :(得分:2)

通过使用localStorage - 正如epascarello和Michael所建议的那样 - 我可以解决这个问题,尽管我怀疑它是最美观的。

以下是文件,也许其他人遇到此问题或者可以在以后建议更好的解决方案:

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>

js文件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.";  
}

欢迎评论/改进!

答案 1 :(得分:1)

我认为您需要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
});

答案 2 :(得分:1)

您只能使用javascript更改当前DOM,但您可以使用例如cookie在一页上更改后显示在两个页面上的数据。优选地,如果您也使用 php或任何服务器端语言,那么可以采用的方法是保存数据库中的条目并将其从那里拉出来。

这是从this answer获取的用于创建和检索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 "";
}

<强> USAGE:

设置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名为&#39; entry&#39;):

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');

}

答案 3 :(得分:1)

在查询字符串中发送

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);