这似乎总是一个问题,我不明白为什么,我试图通过使用他的 ID 来更改元素 p
文本,元素 p id="para1"
位于 PostEditor.html
内:
我要更改的元素ID是以下html
中的para1
:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
以下函数是通过单击 index.html 中的链接并显示您在上面看到的页面来发出的,然后应该更改其内容: 从 index.html 我从链接发出函数:
<a onclick="postEditing()"> Edit</a>
这一行发出以下函数:
function postEditing()
{
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.document.getElementById("para1").innerHTML = "11111111111";
result.document.getElementById("para1").innerText = "11111111111";
result.document.getElementById("para1").value = "11111111111";
}
如您所见,我尝试了三种方法。我永远不明白它们之间有什么区别,但我尝试了所有这三种方法,但都没有用!
最佳答案
这是因为您搜索的是显示index.html 的窗口的文档,而不是新打开的窗口的文档。尝试以下操作:
...
var editorWindow = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
editorWindow.document.getElementById("para1").innerHTML = "11111111111";
...
编辑:
现在我看到了问题:在您试图访问参数 element
的属性的函数中,但您没有为其传递值。所以这将以错误结束,因为访问的对象是 undefinded
!
所以你有三个选项来让它工作:
- 测试参数(总是一个好主意):
var ID = null; if(element) ID = element.id;
- 传递一个值:
<a onclick="postEditing(this)"> Edit</a>
- 删除行
var ID = element.id;
解决方案:(已测试)
我真的说不出为什么,但是 index.html
找到了 para1
并可以成功设置新文本。但不知何故,新窗口将再次重新初始化旧值。
因此,您必须在运行于 onLoad
的处理程序中进行更改:
index.html:
<html>
<head>
<script>
function postEditing() {
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.onload = function() {
result.document.getElementById("para1").innerHTML = "11111111111";
}
}
</script>
</head>
<body>
<a onclick="postEditing()"> Edit</a>
</body>
</html>
PostEditor.html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
关于javascript - 更改元素文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17450611/