gpt4 book ai didi

javascript - 更改另一个页面上的 div 的内容

转载 作者:行者123 更新时间:2023-11-30 08:46:14 24 4
gpt4 key购买 nike

在第 1 页上,我有一个包含信息的 div

<div id='information'></div>

在第 2 页上,我有一个带有 textarea 和一个按钮的 form

<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>

现在我想要的是当我点击提交按钮时,在文本区域输入的文本将被发布到 div#information 改变它之前的内容。
我看过许多其他关于如何更改 div 内容的帖子,但这些与我的问题无关。

最佳答案

一种方法是像其他答案提到的那样,让每个选项卡与中央服务器通信,中央服务器将获取/发送数据,例如使用 AJAX 更新两个选项卡。

但我在这里要告诉你另一种方法,那就是使用我们已经为这类任务设计的东西。什么叫浏览器localStorage

浏览器存储就像这样伪代码:

  //set the value, it works as a hash map or assoc array. 
localStorage .setItem("some_index_key", "some data") ;
// get the value by it's index key.
localStorage .getItem("some_index_key") ; // will get you "some data"

所有数据将在同一域的所有打开的选项卡之间共享。您还可以添加事件监听器,这样每当一个值发生变化时,它就会反射(reflect)在所有选项卡上。

addEvent(window, 'storage', function (event) {
if (event.key == 'some_index_key') {
output.innerHTML = event.newValue;
}
});

addEvent(myInputField, 'keyup', function () {
localStorage.setItem('some_index_key', this.value);
});

看看这个 DEMO ,您在页面 A 上编辑一个字段,该值将离线反射(reflect)在页面 B 上,而无需增加网络负担。

要了解更多信息,read this .

真实的例子。背景颜色由另一个选项卡控制。

     var screenone = document.getElementById('screenone');

screenone.addEventListener('keydown', screenOneFunction);
screenone.addEventListener('change', screenOneFunction);

function screenOneFunction()
{
document.body.style.backgroundColor = this.value;
localStorage.setItem("color1", this.value);
}



var screentwo = document.getElementById('screentwo');

screentwo.addEventListener('keydown', function (evt) {
localStorage.setItem("color2", this.value);
});
screentwo.addEventListener('change', function (evt) {
localStorage.setItem("color2", this.value);
});



var thebutton = document.getElementById('thebutton');

thebutton.addEventListener('click', function (evt) {
localStorage.clear();
screenone.value = "";
screentwo.value = "";
document.body.style.backgroundColor = "";
});



var storageHandler = function () {
document.body.style.backgroundColor = localStorage.color2;
var color1 = localStorage.color1;
var color2 = localStorage.color2;
screenone.value = color2;
screentwo.value = color1;

};
window.addEventListener("storage", storageHandler, false);
       .screenone{ border: 1px solid black;}
input{ margin: 10px; width: 250px; height: 20px; border:round}
label{margin: 15px;}
<html>
<head>
</head>
<body>
<label> Type a color name e.g. red. Or enter a color hex code e.g. #001122 </label>
<br>
<input type="text" class="screenone" id="screenone" />
<label> This tab </label>
<br>
<input type="text" class="screentwo" id="screentwo" />
<label> Other opned tabs </label>
<br>
<input type="button" class=" " id="thebutton" value="clear" />
</body>
</html>

关于javascript - 更改另一个页面上的 div 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21809815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com