简体   繁体   English

JavaScript/jQuery:命名函数

[英]JavaScript/jQuery: naming functions

I found this code online that fulfills my need for one function for my website.我在网上找到了这段代码,它满足了我对网站一项功能的需求。

$(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;

        });
    });

This function primarily enables for the user to upload a csv file of coordinates and then will create markers on the map to mark these locations.此功能主要允许用户上传坐标的 csv 文件,然后在地图上创建标记以标记这些位置。 However, there is no explicit function name stated.但是,没有明确说明函数名称。 This is the html portion:这是html部分:

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

for the user to select the .csv file they want to upload.供用户选择他们想要上传的 .csv 文件。 My question is, how do I implement a similar set of code if I want the users to be able to upload another input .csv file to do other stuff??我的问题是,如果我希望用户能够上传另一个输入 .csv 文件来做其他事情,我该如何实现一组类似的代码? like fundamentally it would be the same, they'll upload a .csv file and the latitudes and longitudes will be extracted to determine the various locations in the input, but I want to add on some other functions to this other .csv file.基本上它是一样的,他们将上传一个 .csv 文件,并提取纬度和经度以确定输入中的各个位置,但我想在另一个 .csv 文件中添加一些其他功能。 Can I just add in a function name like我可以添加一个函数名称,如

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

question

, then for the second time I need this similar function I just add in another script tag starting with ,然后第二次我需要这个类似的功能,我只需添加另一个脚本标签

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

and for the html call secondFunction from an onclick="secondFunction()" or what??对于 html 调用secondFunctiononclick="secondFunction()"或什么? I have very little experience with JavaScript so do forgive me if my question sounds stupid if anything.我对 JavaScript 的经验很少,所以如果我的问题听起来很愚蠢,请原谅我。 I have just been tryna figure this out the entire day and I can't.我一整天都在想办法解决这个问题,但我做不到。 Thanks y'all!谢谢大家!

This is how I think you can do it (there might be different ways, this is what I can think of right now);这就是我认为你可以做到的方式(可能有不同的方法,这是我现在能想到的);

First you make different input s in you HTML with different id's for different tasks.首先,您在 HTML 中使用不同的 id 为不同的任务制作不同的input

Then you put all the code that you need to repeat with each input, inside a function like;然后将需要对每个输入重复的所有代码放在一个函数中,例如:

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;

    });
}

Then for different tasks (for different inputs), we call the function(s) like;然后对于不同的任务(对于不同的输入),我们将函数称为;

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

You put all the above where you have $("#filename").change(function (e) { codes });你把上面所有的东西放在你有$("#filename").change(function (e) { codes }); , as in the question. ,如问题中所述。

Please note that, I do not understand completely how jQuery's .change() works, so I tried to not change anything I thought is related to it, If your code as in the question works as you expect, this should work as well.请注意,我不完全理解 jQuery 的.change()是如何工作的,所以我试图不更改我认为与之相关的任何内容,如果您在问题中的代码按您的预期工作,这也应该工作。

Also please check your part of the codes before actual use, I copied them, so I might have made some mistake;另外请在实际使用前检查您的部分代码,我复制了它们,所以我可能犯了一些错误; But hope you get the answer, and understand what I did.但希望你能得到答案,并理解我所做的。

Check and let me know, and ask if you have any questions!检查并告诉我,并询问您是否有任何问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM