将数据从其他Javascript文件传递给变量

Passing data to variables from other Javascript files

本文关键字:变量 文件 Javascript 数据 其他      更新时间:2023-09-26

我正在做一个让我抓狂的项目,我在这个网站上搜索了很多文章,但我还是不知道怎么做。

我使用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; 
}

geoocation 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 File:

//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 File:

//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 File:

//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");
}

首先,您需要从toDo JavaScript文件中删除findlocation()的代码。调用getFormData函数中的findlocation()

你的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);
}

最后,在find Geolocation文件中应该有如下代码:

function CallTodoStr(todoItem, daysUntilDue) {
    var todoStr = "(" + todoItem.latitude + ", " + todoItem.longitude
                  + ") " + todoItem.who + " needs to " + todoItem.task
                  + " by " + todoItem.dueDate + "  " + daysUntilDue;
    return todoStr;
}