2015-07-22 1 views
0

Я работаю над проектом, который сводит меня с ума, я просматривал статьи здесь, на сайте, но мне не удалось понять, как это сделать сделайте эту работу.Передача данных в переменные из других файлов Javascript

Я использую файл Modernizr.js для проверки геолокации и localStorage, часть localStorage работает отлично, а также находит широту, долготу и создает карту с файлом геолокации. Проблема, с которой я сталкиваюсь, заключается в передаче значений широты и долготы в основной файл js, чтобы я мог передать эти значения (вместе с данными формы, введенными на странице) в функцию-конструктор.

Я не знаю, является ли это порядком моих утверждений или если я передаю данные некорректно, я некоторое время сражаюсь с этим, и мне удалось больше смутить себя. Если кто-то поможет мне это разъяснить, я бы очень признателен.

Я включаю все файлы для этого проекта, снова задерживается только при передаче значений для широты и долготы обратно из файла geolocation.js.

HTML файла:

<!doctype html> 
<html> 
<head> 
    <title>JavaScript, Ajax and JSON: To Do List</title> 
    <meta charset="utf-8"> 
    <link rel="stylesheet" href="toDoL14O2.css"> 
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script> 
    <script src="Modernizr.js"></script> 
    <script> 

    Modernizr.load([ 
     "toDoL14O2.js", 
    { 
     test: Modernizr.geolocation, 
     yep: "L14O2geolocation.js", 
     nope: "L14O2noGeolocation.js" 
    }, 
    { 
     test: Modernizr.localstorage, 
     yep: "L14O2localStorage.js", 
     nope: "L14O2noLocalStorage.js", 
     complete: function() { 
     init(); 
    } 
    } 
    ]); 
</script>   
</head> 
<body> 
<div> 
    <h1>My To Do List</h1> 
    <ul id="todoList"> 
    </ul> 

    <!-- display the map//--> 
    <div id="mapDiv"> 
    <h1>Where To Do It</h1> 
    <div id="map"> 
    </div> 
</div> 

<!-- display the search results //--> 
    <div id="searchResults"> 
    <h2>Results</h2> 
    <ul id="searchResultsList"> 
    </ul> 
    </div> 

<form> 
<!-- display the search input //--> 
    <fieldset> 
    <legend>Search to do items</legend> 
    <div class="tableContainer"> 
    <div class="tableRow"> 
    <label for="searchTerm">Search: </label> 
     <input type="text" id="searchTerm" size="35" 
       placeholder="search term"> 
    </div> 
    <div class="tableRow"> 
    <label for="searchButton"></label> 
    <input type="button" id="searchButton" value="Search"> 
    </div> 
</fieldset> 

<fieldset> 
<legend>Add a new to do item</legend> 
<div class="tableContainer"> 
<div class="tableRow"> 
    <label for="task">Task: </label> 
     <input type="text" id="task" size="35" placeholder="get milk"> 
</div> 
<div class="tableRow"> 
    <label for="who">Who should do it: </label> 
     <input type="text" id="who" placeholder="Scott"> 
</div> 
<div class="tableRow"> 
      <label for="dueDate">Due Date: </label> 
     <input type="date" id="dueDate" placeholder="mm/dd/yyyy"> 
</div> 
<div class="tableRow"> 
    <label for="submit"></label> 
    <input type="button" id="submit" value="submit"> 
</div> 
</fieldset> 
</form> 
</div> 
</body> 
</html> 

Todo JavaScript Файл:

function Todo(id, task, who, dueDate, days, lat, lon) { 
    this.id = id; 
    this.task = task; 
    this.who = who; 
    this.dueDate = dueDate; 
    this.done = false; 
    this.days = days; 
    this.lat = lat; 
    this.lon = lon; 
} 

var todos = new Array(); 

var lat; 
var lon; 
console.log("Before Onload: " + lat + ", " + lon); 

window.onload = init; 
function init() { 
var submitButton = document.getElementById("submit"); 
submitButton.onclick = getFormData; 

// get the search term and call the click handler 
var searchButton = document.getElementById("searchButton"); 
searchButton.onclick = searchTodos; 

getTodoItems(); 
} 

function getTodoItems() { 
    if (localStorage) { 
    for (var i = 0; i < localStorage.length; i++) { 
     var key = localStorage.key(i); 
     if (key.substring(0, 4) == "todo") { 
      var item = localStorage.getItem(key); 
      var todoItem = JSON.parse(item); 
      todos.push(todoItem); 
     } 
    } 
    addTodosToPage(); 
    } 
    else { 
    console.log("Error: you don't have localStorage!"); 
    } 
} 

function addTodosToPage() { 
    var ul = document.getElementById("todoList"); 
    var listFragment = document.createDocumentFragment(); 
    for (var i = 0; i < todos.length; i++) { 
    var todoItem = todos[i]; 
    var li = createNewTodo(todoItem); 
    listFragment.appendChild(li); 
    } 
    ul.appendChild(listFragment); 
} 

function addTodoToPage(todoItem) { 
    var ul = document.getElementById("todoList"); 
    var li = createNewTodo(todoItem); 
    ul.appendChild(li); 
    document.forms[0].reset(); 
} 

function createNewTodo(todoItem) { 
    var li = document.createElement("li"); 
    li.setAttribute("id", todoItem.id); 

    var spanTodo = document.createElement("span"); 
    spanTodo.innerHTML = 
    todoItem.who + " needs to " + todoItem.task + " by " + 
    todoItem.dueDate + " at Lat: " + todoItem.lat + " & Lon: " + 
     todoItem.lon + "Task has " + todoItem.days + " days until due"; 

    var spanDone = document.createElement("span"); 
    if (!todoItem.done) { 
    spanDone.setAttribute("class", "notDone"); 
    spanDone.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; 
    } 
    else { 
     spanDone.setAttribute("class", "done"); 
     spanDone.innerHTML = "&nbsp;&#10004;&nbsp;"; 
    } 

// add the click handler to update the done state 
    spanDone.onclick = updateDone; 

// add the delete link 
    var spanDelete = document.createElement("span"); 
    spanDelete.setAttribute("class", "delete"); 
    spanDelete.innerHTML = "&nbsp;&#10007;&nbsp;"; 

// add the click handler to delete 
    spanDelete.onclick = deleteItem; 

    li.appendChild(spanDone); 
    li.appendChild(spanTodo); 
    li.appendChild(spanDelete); 

    return li; 
} 

function getFormData() { 
    var task = document.getElementById("task").value; 
    if (checkInputText(task, "Please enter a task")) return; 

    var who = document.getElementById("who").value; 
    if (checkInputText(who, "Please enter a person to do the task")) 
    return; 

    var date = document.getElementById("dueDate").value; 
    if (checkInputText(date, "Please enter a due date")) return; 

// later, process date here 
//send date input to checkDate function, will validate correct format 
//and return value for how many days until due or how many days overdue. 
checkDate(date); 
    var numOfDays; 
    calculateDays(date); 

    var id = (new Date()).getTime(); 

//The findLocation function will call either the L14O2geolocation.js or 
//the L14O2noGeolocation.js files, using the Modernizr.js file to check 
//to see if geolocation is enabled, if so will display map where to do 
//item is to be done and if not will return message no geolocation is 
//enbled. 

//var lat; 
//var lon; 

findLocation(lat, lon); 

    console.log("Return lat and long! " + lat + ", " + lon); 

    var todoItem = new Todo(id, task, who, date, lat, lon); 
    todos.push(todoItem); 
    addTodoToPage(todoItem); 
    saveToDoItem(todoItem); 

// hide search results 
    hideSearchResults(); 
} 

function checkInputText(value, msg) { 
    if (value == null || value == "") { 
    alert(msg); 
    return true; 
    } 
    return false; 
} 

//Move this function to the L14O2localStorage.js and 
//14O2noLocalStorage.js files. 
//function saveTodoItem(todoItem) { 
// if (localStorage) { 
//  var key = "todo" + todoItem.id; 
//  var item = JSON.stringify(todoItem); 
//  localStorage.setItem(key, item); 
// } 
// else { 
//  console.log("Error: you don't have localStorage!"); 
// } 
//} 

function updateDone(e) { 
var span = e.target; 
var id = span.parentElement.id; 
var item; 
    for (var i = 0; i < todos.length; i++) { 
    if (todos[i].id == id) { 
     item = todos[i]; 
     break; 
    } 
} 
if (item.done == false) { 
    item.done = true; 
    span.setAttribute("class", "done"); 
    span.innerHTML = "&nbsp;&#10004;&nbsp;"; 
} 
else if (item.done == true) { 
    item.done = false; 
    span.setAttribute("class", "notDone"); 
    span.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; 
} 
    var itemJson = JSON.stringify(item); 
    var key = "todo" + id; 
    localStorage.setItem(key, itemJson); 
} 

function deleteItem(e) { 
    var span = e.target; 
    var id = span.parentElement.id; 

    // find and remove the item in localStorage 
    var key = "todo" + id; 
    localStorage.removeItem(key); 

    // find and remove the item in the array 
    for (var i = 0; i < todos.length; i++) { 
    if (todos[i].id == id) { 
     todos.splice(i, 1); 
     break; 
    } 
    } 

// find and remove the item in the page 
    var li = e.target.parentElement; 
    var ul = document.getElementById("todoList"); 
    ul.removeChild(li); 

//clear map from page 
    var map = document.getElementById("map"); 
    map.innerHTML = ""; 

// hide search results 
    hideSearchResults(); 
} 

// Search 
function searchTodos() { 
    // new search, so clear previous results 
    clearSearchResultsList(); 
    // get the text to search for 
    var searchTerm = document.getElementById("searchTerm").value; 
    var count = 0; 
    // check all the todos in the list 
    for (var i = 0; i < todos.length; i++) { 
    var todoItem = todos[i]; 
    // make a regular expression to match the search term, regardless of 
    //case 
    var re = new RegExp(searchTerm, "i"); 
    // try matching the expression with the task and the who from the to 
    //do item 
    if (todoItem.task.match(re) || todoItem.who.match(re)) { 
     // if we find a match, add the to do item to the search results 
     addSearchResultToPage(todoItem); 
     // keep a count of the number of items we match 
     count++; 
    } 
    } 
    // if we don't match any items, display "no results" 
    if (count == 0) { 
     var ul = document.getElementById("searchResultsList"); 
     var li = document.createElement("li"); 
     li.innerHTML = "No results!"; 
     ul.appendChild(li); 
    } 
    // show the search results 
    showSearchResults(); 
} 

// add a search result to the search results list in the page 
function addSearchResultToPage(todoItem) { 
    var ul = document.getElementById("searchResultsList"); 
    var li = document.createElement("li"); 
    li.innerHTML = 
    todoItem.who + " needs to " + todoItem.task + " by " + 
     todoItem.dueDate; 
    ul.appendChild(li); 
} 

// clear the previous search results 
function clearSearchResultsList() { 
    var ul = document.getElementById("searchResultsList"); 
    while (ul.firstChild) { 
    ul.removeChild(ul.firstChild); 
    } 
} 

function hideSearchResults() { 
    var div = document.getElementById("searchResults"); 
    div.style.display = "none"; 
    clearSearchResultsList(); 
} 

function showSearchResults() { 
    var div = document.getElementById("searchResults"); 
    div.style.display = "block"; 
    document.forms[0].reset(); 
} 

function checkDate(date) { 
    if (isValidDate(date) == false) { 
    return false; 
    } 
    console.log(date + " is a valid date"); 
    return true; 
} 

function isValidDate(date) { 
// Checks for the following valid date format of mm/dd/yyyy 
// mm/dd/yyyy and yyyy/mm/dd 

    var regEx1 = /^(\d{2,2})(\/)(\d{2,2})\2(\d{4}|\d{4})$/; 
// var regEx2 = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; 
//if (date != "" && date.match(regEx1) && date.match(regEx2)) 
if (date != "" && date.match(regEx1)) { 
    alert("Invalid Date Format: " + date); 
    return false; 
} 
return true; 
} 

//Function to calculate the number of days until an item is either due 
//or overdue. 
function calculateDays(date) { 
var today = new Date(); 
var d1 = today.getTime(); 
var dateIn = new Date(date); 
var d2 = dateIn.getTime(); 
var year = today.getFullYear(); 
var month = today.getMonth()+1; 
var day = today.getDate(); 
var time = today.getTime(); 

var total = parseInt((d1-d2)/(24*3600*1000)); 
console.log("Total: " + total); 
return total; 
} 

геолокации JavaScript Файл:

//If geolocation is found by Modernizr the map where the to do item is 
//to be completed will be displayed in the mapDiv on the page. 
function findLocation(lat, lon) { 
    console.log("In Geolocation"); 
    navigator.geolocation.getCurrentPosition(displayLocation); 
} 

function displayLocation(position) { 
    var map = null; 

    latitude = position.coords.latitude; 
    longitude = position.coords.longitude; 

    lat = latitude; 
    lon = longitude; 

    console.log("Lat: " + lat + " Lon: " + lon); 

    if (!map) { 
    showMap(latitude, longitude); 
    } 
    addMarker(latitude, longitude); 
    return(lat, lon); 
} 

function showMap(lat, long) { 
    var googleLatLong = new google.maps.LatLng(lat, long); 
    var mapOptions = { 
    zoom: 12, 
    center: googleLatLong, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
}; 
    var mapDiv = document.getElementById("map"); 
    map = new google.maps.Map(mapDiv, mapOptions); 
    map.panTo(googleLatLong); 
} 

function addMarker(lat, long) { 
    var googleLatLong = new google.maps.LatLng(lat, long); 
    var markerOptions = { 
    position: googleLatLong, 
    map: map, 
    title: "Task Location" 
} 
var marker = new google.maps.Marker(markerOptions); 
} 

noGeolocation JavaScript Файл:

//If geolocation is not found by Modernizr a message will be displayed 
//in the console and on the page showing that geolocation is not enabled. 
function findLocation() { 
    var mapDiv = document.getElementById("map"); 
    mapDiv.innerHTML = "Geolocation is not enabled on this browser."; 
    console.log("Geolocation is not enabled on this browser."); 
} 

LocalStorage JavaScript Файл:

//If localStorage is found by Modernizr the to do item will be stored in 
//localStorage and message displayed in the console. 
function saveToDoItem(todoItem) { 
    var key = "todo" + todoItem.id; 
    var item = JSON.stringify(todoItem); 
    localStorage.setItem(key, item); 
    console.log("Item: " + key + ", " + item + " stored in local storage"); 
} 

noLocalStorage JavaScript Файл:

//If localStorage is found by Modernizr the to do item will be stored in 
//localStorage and message displayed in the console. 
function saveToDoItem(todoItem) { 
    var key = "todo" + todoItem.id; 
    var item = JSON.stringify(todoItem); 
    localStorage.setItem(key, item); 
    console.log("Item: " + key + ", " + item + " stored in local storage"); 
} 

ответ

0

Во-первых, вам нужно удалить код findlocation() из вашего toDo JavaScript файла. Вызвать findlocation() в функции getFormData.

Ваш createNewTodo() код должен начинаться с:

function createNewTodo(todoItem) { 
    var li = document.createElement("li"); 
    li.setAttribute("id", todoItem.id); 
    var spanTodo = document.createElement("span"); 
    var daysUntilDue = calcDaysLeft(todoItem.dueDate); 
    spanTodo.innerHTML = CallTodoStr(todoItem, daysUntilDue); 
} 

Наконец, вы должны иметь код, как это в вашей находки геолокация файла:

function CallTodoStr(todoItem, daysUntilDue) { 
    var todoStr = "(" + todoItem.latitude + ", " + todoItem.longitude 
        + ") " + todoItem.who + " needs to " + todoItem.task 
        + " by " + todoItem.dueDate + " " + daysUntilDue; 
    return todoStr; 
} 
Смежные вопросы