所以我有一个应用程序,它允许你添加数据,然后它显示所有数据(仍然是wip)。所以我到目前为止使用localStorage和jQueryMobile以及jQueryUI创建了一个Create和Read功能。
但由于某种原因,当我在页面之间切换(主页/添加数据页面)时,我在主页面上看到了克隆数据。我看到4个条目,而不是2个条目,它的原始2个条目彼此有一个副本。当我刷新页面它工作正常时,它只显示原始数据,没有克隆。请注意,只有当您转到添加页面然后返回主页面时(通过单击主页按钮)才会发生这种情况。
此外,当您添加运行时,由于某种原因,它同时添加2次运行(运行添加功能2次)
以下是代码:
document.getElementById('myButton').addEventListener('click', function () {
var clickCount = parseInt(this.getAttribute('data-clicked'), 10);
// Get clicked count from the data attribute
if (clickCount++ % 2) {
// If clicked count odd
document.getElementById('myUl').style.height = '0px';
} else {
// if clicked count is even
document.getElementById('myUl').style.height = '100px';
}
this.setAttribute('data-clicked', clickCount);
// Updated clicked count by one
}, false);
$(document).on('pageinit', function() {
//Display runs
showRuns();
//Add Handler for Adding Runs
$('#submitAdd').on('tap', addRun);
/*
* Show all runs on homepage
*/
function showRuns() {
//get runs Object
var runs = getRunsObject();
var i = 0;
if (runs != '' && runs != null) {
for (i; i < runs.length; i++) {
$('#stats').append('<li class="ui-body-inherit ui-li-static"><strong>Date: </strong>' + runs[i]["date"] + '<strong> <br/>Distnace: </strong>' + runs[i]["kms"] + 'km</li>');
}
$('#home').bind('pageinit', function() {
$('#stats').listview('refresh');
});
}
}
/*
* addRun function
*/
function addRun() {
//Get form values
var kms = $('#addKms').val();
var date = $('#addDate').val();
//Create 'Run' Object
var run = {
date: date,
kms: parseFloat(kms)
};
var runs = getRunsObject();
//Add run to runs array
runs.push(run);
alert('Run Added');
//Set stringified objects to localstorage
localStorage.setItem('runs', JSON.stringify(runs));
//Redirect
window.location.href = "index.php";
//Preventing form from submiting
return false;
}
/*
* getRunsObject
*/
function getRunsObject() {
//Set runs array
var runs = [];
//Get current runs from localStorage
var currentRuns = localStorage.getItem('runs');
//Check localStorage
if (currentRuns != null) {
//Set to runs
var runs = JSON.parse(currentRuns);
}
//Return sorted runs object
return runs.sort(function(a, b) {
return new Date(b.date) - new Date(a.date);
});
}
});
body {
text-align: center;
}
ul {
display: block;
}
.controls {
float: right;
}
由于某些原因,示例未在StackOverflow上加载,因此这里是现场演示:
http://runningtracker.herokuapp.com/index.php
尝试添加新的运行,然后切换回添加页面,然后返回主页。
答案 0 :(得分:1)
好吧,我找到了解决方案。我换了:
$(document).on('pageinit', function() {});
使用:
$(document).one('pageinit', function() {});
据我了解,我有2页,所以每个功能都运行了两次,这导致了我的问题。使用one
代替on
我强制所有脚本只运行一次,无论我有多少页。
答案 1 :(得分:1)
问题出在pageinit
事件处理中。您省略了选择器,因此处理程序被调用两次(对于home
和add
页面),并且这样做两次调用$('#submitAdd').on('tap', addRun);
,导致双{{1}调用。
用以下代码更改行:
addRun
($(document).on("pagecreate", "#home", function() {
现在替换pagecreate
,请参阅jQM API)
另外,请更改“重定向”,删除pageinit
。
该指令改变了绕过jQuery Mobile导航系统的页面,结果是在每次window.location.href = "index.php";
调用后调用pageinit
事件(虽然它应该只调用一次)。
使用change方法更改您的页面:
addRun