我使用本地存储将用户名保存在first-page.html中并将其检索到second-page.html
但是如果我在我的第二页面中有两个或更多位置我想要检索用户名,我怎样才能使用两个不同的ID来实现它。由于曾经使用的id不能在另一个输入字段中使用。 任何人都可以帮忙。
的index.html:
<script>
function save(){
var fieldValue = document.getElementById('user').value;
localStorage.setItem('text', fieldValue);
}
</script>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-user"></span></i>
</span>
<input type="text" name="user" id="user" placeholder="Username" class="form-control" required/>
</div>
</div>
</div>
<input class="view sign-in-app" type="submit" value="Sign In" id="submit-login" onclick="save()" />
SecondPage.html
<script>
function load(){
var storedValue = localStorage.getItem('text');
if(storedValue){
document.getElementById('here').value = storedValue;
}
}
</script>
<body onload="load()">
<!-- first div -->
<div class="form-group">
<div class="cols-sm-10">
<div class="input-group">
<input type="text" name="userName" id="here" class="form-control" placeholder="Username" required>
</div>
</div>
</div>
<!-- second div -->
<div class="form-group">
<div class="cols-sm-10">
<div class="input-group"> // change the id here
<input type="text" name="userName" id="here" class="form-control" placeholder="Username" required>
</div>
</div>
</div>
</body>
答案 0 :(得分:0)
确实给每个元素赋予不同的ID。没问题。然后在设置时,设置两个:
if (storedValue) {
document.getElementById('here').value = storedValue;
document.getElementById('my-other-id').value = storedValue;
}