2015-10-29 3 views
-1

Я нашел этот код онлайн, который соответствует моей потребности в одной функции для моего сайта.JavaScript/jQuery: функции именования

$(document).ready(function() { 
     var markers = []; // define global array in script tag so you can use it in whole page 
     var myCenter = new google.maps.LatLng(1.3000, 103.8000); 
     var mapProp = { 
      center: myCenter, 
      zoom: 6, 
      minZoom: 6, 
      mapTypeId: google.maps.MapTypeId.ROADMAP, 
      mapTypeControl: true 
     }; 
     //google map object 
     var map = new google.maps.Map(document.getElementById("map"), mapProp); 

     //change event of input tag where type=file and id=filename 
     $("#filename").change(function (e) { 

      var ext = $("input#filename").val().split(".").pop().toLowerCase(); 

      if ($.inArray(ext, ["csv"]) == -1) { 
       alert('Upload CSV'); 
       return false; 
      } 

      if (e.target.files != undefined) { 

       var reader = new FileReader(); 
       reader.onload = function (e) { 

        var csvval = e.target.result.split("\n"); 
        var csvvalue; 

        for (var i = 0; i < csvval.length; i++) { 
         markers[i] = []; 
         csvvalue = csvval[i].split(","); 
         markers[i][0] = csvvalue[0]; //id 
         var lat = csvvalue[2]; //latitude 
         var lng = csvvalue[3]; //longitude 

         var code = csvvalue[0]; 


         if (code.includes("AB")) { 
          var nsMarker = new google.maps.Marker({ 
           icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png', 
           position: new google.maps.LatLng(lat, lng), 
           map: map 

          }); 



         } else if (code.includes('CD')) { 
          var ewMarker = new google.maps.Marker({ 
           icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', 
           position: new google.maps.LatLng(lat, lng), 
           map: map 
          }); 

         } else if (code.includes('EF')) { 
          var neMarker = new google.maps.Marker({ 
           icon: 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png', 
           position: new google.maps.LatLng(lat, lng), 
           map: map 
          }); 

         } else if (code.includes('GH')) { 
          var ccMarker = new google.maps.Marker({ 
           icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png', 
           position: new google.maps.LatLng(lat, lng), 
           map: map 
          }); 

         } else if (code.includes('IJ')) { 
          var dtMarker = new google.maps.Marker({ 
           icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', 
           position: new google.maps.LatLng(lat, lng), 
           map: map 
          }); 

         } else if (code.includes('KL')) { 
          var cgMarker = new google.maps.Marker({ 
           icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', 
           position: new google.maps.LatLng(lat, lng), 
           map: map 
          }); 

         } 

         //markers[i][1] = new google.maps.Marker({ 
         // position: new google.maps.LatLng(lat, lng), 
         // map: map 
         //}); 
        } 

       }; 
       reader.readAsText(e.target.files.item(0)); 
      } 

      return false; 

     }); 
    }); 

Эта функция в первую очередь дает возможность для пользователя, чтобы загрузить CSV-файл координат, а затем будет создавать маркеры на карте, чтобы пометить эти места. Однако не указано явное имя функции. Это часть html:

<input type="file" id="filename" name="filename" /> 

для пользователя, чтобы выбрать файл CSV, который они хотят загрузить Мой вопрос: как мне реализовать подобный набор кода, если я хочу, чтобы пользователи могли загружать другой файл ввода .csv, чтобы делать другие вещи? как и в принципе, это будет то же самое, они загрузят файл .csv, и широты и долготы будут извлечены, чтобы определить различные местоположения на входе, но я хочу добавить некоторые другие функции к этому другому CSV-файлу. Могу ли я просто добавить в имени функции, как

$(document).ready(function() readAllLocations { ... // for the FIRST .csv in 

вопрос

, а затем во второй раз мне нужна эта же функция, я просто добавьте в другом теге сценария, начиная с

$(document).ready(function() secondFunction {.... 

и для html-вызов secondFunction от onclick="secondFunction()" или что ?? У меня очень мало опыта работы с JavaScript, так что простите меня, если мой вопрос звучит глупо. Я только что попробовал это весь день, и я не могу. Благодарю вас!

+2

Первый; В основном вы используете jQuery. Во-вторых, Я все еще пытаюсь понять вас лучше, но часть '$ (document) .ready (function() {codes});' проверяет, готова ли DOM, затем коды внутри нее выполняются, вам не нужно повторять что. И в JavaScript вы объявляете новую функцию, например; 'function first() {codes}', где «first» - это имя функции. то вы можете называть их столько раз, сколько вам нужно; 'Первый();'. – Person

ответ

0

Вот как я думаю, вы можете это сделать (могут быть разные способы, это то, о чем я могу думать прямо сейчас);

Сначала вы делаете разные input s в своем HTML с разными идентификаторами для разных задач.

Затем вы помещаете весь код, который вам нужно повторять с каждым входом, внутри функции;

function processInput (selector, callback) { 
    $(selector).change(function (e) {  
     var ext = $(this).val().split(".").pop().toLowerCase(); 
     // Here "this" refers to the selector. 

     if ($.inArray(ext, ["csv"]) == -1) { 
      alert('Upload CSV'); 
      return false; 
     } 

     if (e.target.files != undefined) { 

      var reader = new FileReader(); 
      reader.onload = function (e) { 

       var csvval = e.target.result.split("\n"); 
       var csvvalue; 

       for (var i = 0; i < csvval.length; i++) { 
        markers[i] = []; 
        csvvalue = csvval[i].split(","); 
        markers[i][0] = csvvalue[0]; //id 
        var lat = csvvalue[2]; //latitude 
        var lng = csvvalue[3]; //longitude 

        var code = csvvalue[0]; 


        if (code.includes("AB")) { 
         var nsMarker = new google.maps.Marker({ 
          icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png', 
          position: new google.maps.LatLng(lat, lng), 
          map: map 

         }); 


        } else if (code.includes('CD')) { 
         var ewMarker = new google.maps.Marker({ 
          icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', 
          position: new google.maps.LatLng(lat, lng), 
          map: map 
         }); 

        } else if (code.includes('EF')) { 
         var neMarker = new google.maps.Marker({ 
          icon: 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png', 
          position: new google.maps.LatLng(lat, lng), 
          map: map 
         }); 

        } else if (code.includes('GH')) { 
         var ccMarker = new google.maps.Marker({ 
          icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png', 
          position: new google.maps.LatLng(lat, lng), 
          map: map 
         }); 

        } else if (code.includes('IJ')) { 
         var dtMarker = new google.maps.Marker({ 
          icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', 
          position: new google.maps.LatLng(lat, lng), 
          map: map 
         }); 

        } else if (code.includes('KL')) { 
         var cgMarker = new google.maps.Marker({ 
          icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', 
          position: new google.maps.LatLng(lat, lng), 
          map: map 
         }); 

        } 

        // I am assuming this is where you wish to do different tasks, 
        // feel free to move the block below, to where you need. 

        if(typeof callback === 'function' && callback()){ 
         // Here the "if" staement checks if "callback" is a function, 
         // you may remove it if you do not need to check. 

         callback(i); 
         // This is for the different tasks. 
         // We're passing "i" as parameter to use when we call the function. 
        } 

        //markers[i][1] = new google.maps.Marker({ 
        // position: new google.maps.LatLng(lat, lng), 
        // map: map 
        //}); 
       } 

      }; 
      reader.readAsText(e.target.files.item(0)); 
     } 

     return false; 

    }); 
} 

Затем для различных задач (для разных входов) мы называем такие функции;

processInput("#filename", function(i) { 
    // ..And this is how you would call the function. 

    //markers[i][1] = new google.maps.Marker({ 
    // position: new google.maps.LatLng(lat, lng), 
    // map: map 
    //}); 
}); 

processInput("#secondfile", function(i) { 
    // ..And as many times you need. 
    // Put the tasks you want to do for the input with id "#secondfile" below; 

    //markers[i][1] = new google.maps.Marker({ 
    // position: new google.maps.LatLng(lat, lng), 
    // map: map 
    //}); 
}); 

Вы помещаете все выше, где у вас есть $("#filename").change(function (e) { codes });, как и в вопросе.

Обратите внимание, что я не совсем понимаю, как работает jQuery .change(), поэтому я старался не изменять ничего, что я думал о нем, если ваш код как в вопросе работает так, как вы ожидаете, это тоже должно работать.

Также, пожалуйста, проверьте свою часть кода перед фактическим использованием, я скопировал их, поэтому я, возможно, допустил ошибку; Но надеюсь, что вы получите ответ и поймете, что я сделал.

Проверьте и дайте мне знать и спросите, есть ли у вас какие-либо вопросы!

Смежные вопросы