gpt4 book ai didi

javascript - 修改 html (DOM) 后丢失更改

转载 作者:行者123 更新时间:2023-11-28 06:15:51 27 4
gpt4 key购买 nike

我使用带有 chrome 扩展的 netbeans(netbeans 连接器),我创建了一个如下所示的 jsp 页面:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Page</title>
</head>
<body>
<div align = "center">
<form >
<table border="0">
<tbody>
<tr>
<td>Name : </td>
<td><input type="text" name="Name" value="" /></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="Password" value="" /></td>
</tr>
<tr>
<td>Age : </td>
<td><input type="text" name="Age" value="" /></td>
</tr>
<tr>
<td></td>
<td><input type="reset" value="Reset" style="float: right"/>
<input type="submit" value="Submit" style="float: right" onclick="onSubmit()" />
</td>
</tr>
</tbody>
</table>
</form>
</div>


<div align = "center">
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>

</tbody>
</table>


</div>


<script language = "javascript">
function onSubmit(){
var name = document.getElementsByName('Name')[0] ;
var password = document.getElementsByName('Password')[0] ;
var age = document.getElementsByName('Age')[0] ;

if(age.value >= 50){
alert('You\'re too old !');
}

var table = document.getElementsByTagName('table')[1] ;
var body = table.getElementsByTagName('tbody')[0] ;
var trNode = document.createElement('tr') ;
var thNameNode = document.createElement('td') ;
var nameTextNode = document.createTextNode(name.value.toString()) ;
thNameNode.appendChild(nameTextNode) ;
var thAgeNode = document.createElement('td') ;
var ageTextNode = document.createTextNode(age.value) ;
thAgeNode.appendChild(ageTextNode) ;

trNode.appendChild(thNameNode) ;
trNode.appendChild(thAgeNode) ;

body.appendChild(trNode) ;
}
</script>
</body>

函数onSubmit()应该动态地在表中添加一行,但是当我在浏览器上运行时,更改会短暂出现,然后我再次重定向到原始页面,到底是什么有问题吗?

最佳答案

表单在onSubmit函数上提交,您可以通过return false来阻止它。所以下面应该可以工作

 function onSubmit(){
var name = document.getElementsByName('Name')[0] ;
var password = document.getElementsByName('Password')[0] ;
var age = document.getElementsByName('Age')[0] ;

if(age.value >= 50){
alert('You\'re too old !');
}

var table = document.getElementsByTagName('table')[1] ;
var body = table.getElementsByTagName('tbody')[0] ;
var trNode = document.createElement('tr') ;
var thNameNode = document.createElement('td') ;
var nameTextNode = document.createTextNode(name.value.toString()) ;
thNameNode.appendChild(nameTextNode) ;
var thAgeNode = document.createElement('td') ;
var ageTextNode = document.createTextNode(age.value) ;
thAgeNode.appendChild(ageTextNode) ;

trNode.appendChild(thNameNode) ;
trNode.appendChild(thAgeNode) ;

body.appendChild(trNode) ;
return false;
}

关于javascript - 修改 html (DOM) 后丢失更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973371/

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