【问题标题】:Send from one HTML page to another with two different js使用两个不同的 js 从一个 HTML 页面发送到另一个页面
【发布时间】:2019-06-18 08:40:52
【问题描述】:

我在主页上使用 HTML 和 JS 将变量发送到另一个 js 页面。

我这样做了 在页面索引中,我使用 index.js 创建按钮

<a href="index.html" id= "button1">Easy</a>

在 index .js 中我做了这个

window.addEventListener('load', function(){
document.getElementById("button1").onclick = function(){
    sessionStorage.setItem("mood", '1');
    window.location.replace("second.html");
};

在 second.js 中,我在 js 中这样做是为了获取情绪变量。

data = sessionStorage.getItem('mood');

在 Firefox 上一切正常(在本地),但是当使用 Chrome o 在线上传时,按钮不起作用,因为它不会重定向到 second.html

有人可以帮助我吗? p.s 我不想使用脚本(Ajax、Jquery 等)

【问题讨论】:

  • button1 是指进入 second.html 还是 index.html?
  • button1 调用 index.html 有 index.js 替换为 second.html
  • 但是你的 button1 href = "index.html" 但是在 onclick 你希望它转到 "second.html"?
  • 是的,变量。但我不能做“href =second.html”,因为不要调用 index.js onclick 方法,也不要设置变量 mood @Jaxi
  • 酷。我会写一个快速的答案,以便可以接受,否则问题将被保留为“未回答”

标签: javascript html session button interaction


【解决方案1】:

正如我的评论中所述,将 href 设置为“#”,或将其从 a 标签切换为按钮标签将防止双页直接,而是运行 onclick 功能,设置您的存储然后重定向到index.html 中的 second.html。

例子:

&lt;a href="#" id="button1"&gt;Easy&lt;/a&gt;

或&lt;button id="button1" onclick="loadB1()" &gt;Easy&lt;/button&gt;

并以这种方式在 index.js 中调用函数:

function loadB1(){
sessionStorage.setItem("mood", '1');
window.location.replace("second.html");
};

【讨论】:

    【解决方案2】:

    这不是一种常见的做法,但你可以使用 browserify https://www.npmjs.com/package/browserify 或需要js https://www.npmjs.com/package/requirejs 并以自己的方式“Nodish”风格。

    编辑: 如果您直接引用其他文件,我认为它会按您的方式工作。

    window.addEventListener('load', function(){
    document.getElementById("button1").onclick = function(){
    sessionStorage.setItem("mood", '1');
     window.location = "http://yourURL.yourURL.com/ourPath/second.html"; 
    };
    

    【讨论】:

    • 我可以不用外部脚本吗?我只是希望传递一个简单的变量,使用其他js工具似乎太多了
    • 不,亲爱的,不工作我使用了@Jaxi 的解决方案并且工作正常!
    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2012-12-21
    • 2022-01-15
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多