简体   繁体   English

HTML getElementById更改另一个html文件中的元素

[英]Html getElementById to change an element in another html file

I am learning HTML and Javascript, and for an assignment I need to get a button to change an element to another HTML file. 我正在学习HTML和Javascript,对于作业,我需要获得一个将元素更改为另一个HTML文件的按钮。

Here is my code: 这是我的代码:

main.html main.html

</head>
    <script src="testscript.js"></script>
</head>

<body>
    <button onclick="button1()">Function 1</button>
</body>

testscript.js testscript.js

function button1(){
var value = confirm("Press anything");

if(value == 1){
    document.getElementById("abc").innerHTML = "Ok";
    window.location.assign("button1.html");}   
}

button1.html button1.html

<body>  
    <p id="abc"></p>
</body>

So basically, button1() gets called from main.html and needs to change the value of an element in button1.html. 因此,基本上,从main.html调用button1(),并且需要更改button1.html中元素的值。

A similar example is illustrated here: (link) . 此处显示了一个类似的示例:( 链接) I have also tried outerHTML but it doesn't work either. 我也尝试过externalHTML,但它也不起作用。 Is this not possible? 这不可能吗? I can't find anything online. 我在网上找不到任何东西。

Note: My html and js files have to be separated. 注意: 我的html和js文件必须分开。

Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

First: Inline event handling is not a best practice; 第一:内联事件处理不是最佳实践; instead give your button an ID and attach an event handler to it. 而是给按钮一个ID并为其附加事件处理程序。

Second: Any DOM manipulations should be handled after the DOM has loaded; 第二:任何DOM操作应该在DOM加载进行处理; either move your JS to the bottom just before the closing body tag, or use window.onload . 您可以将JS移到body标记之前的底部,或者使用window.onload

So, if you have the following HTML: 因此,如果您具有以下HTML:

<button id="f1">Function1</button>

...then, you should have something like this in your JS file: ...然后,您的JS文件中应包含以下内容:

window.onload = function() {
    document.getElementById('f1').onclick = function() {
    var value = prompt("Press anything");
    };
};

To pass data between pages you can use cookies, localStorage or URL query parameters . 要在页面之间传递数据, 您可以使用Cookie,localStorage或URL查询参数

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

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