如何从函数中调用变量

时间:2019-05-23 20:05:17

标签: javascript

我似乎无法通过脚本调用较早的变量集来控制元素。

将地图加载到页面上的脚本

<script>
window.scribblemaps = {
    settings: {
        baseAPI: "google",
        key: 'key'
    }
};

var loadmap = function () {
    var sm = new 
        scribblemaps.ScribbleMap(document.getElementById('ScribbleMap'),
            { controlMode: { 'mapType': scribblemaps.ControlModes.SMALL } }
    );
}
</script>

html会创建一个div以显示地图

<div class="SM" id="ScribbleMap"></div>

使用JavaScript保存地图

(function($) {

    $(document).ready(function() {
        $('#start_design').click(function(){
            var id = $(this).attr('href');
            var offset = $(id).offset().top - 70;
            $('body, html').animate({scrollTop: offset}, 1000);
        })

        $('#save_design_maps').on('click',function(){
            var project_name = $('#project_name');
            if( project_name.val() !== '') {
                project_name.css('border-color', '');
                var sm = document.getElementById('ScribbleMap');
                var uid = (new Date().getTime()).toString(36);
                var title = project_name.val();
                var details = {
                    "id": uid,
                    "password": "aaa",
                    "title": title,
                    "description": title,
                    "secure": false,
                    "listed": false,
                    "projectId": "ID",
                    "groupCode": "<groupCode>"
                };
                // console.log(sm);
                // console.log(JSON.stringify(sm.data.getSmJSON(), null, 2));

                sm.map.save(details, function (completeEvent) { }, function (errorEvent) { });
                sm.map.addListener(scribblemaps.MapEvent.MAP_SAVED, function (event) {
                    alert('Map is saved!');
                    var sm_share_link = 'https://www.scribblemaps.com/maps/view/' + title.replace(/\s+/g, '_') + '/' + uid;
                    $('#map_url').val(sm_share_link);
                    console.log(sm_share_link);
                });

                sm.map.addListener(scribblemaps.MapEvent.MAP_SAVE_ERROR, function (event) {
                    alert('Map can not be saved!');
                });
            } else {
                alert('Please fill the Project Name Field');
                project_name.css('border-color', 'red');
            }

        });

    });

    $(window).scroll(function() {

    });

    $(window).resize(function() {

    });

    $(window).load(function() {

    });
})(jQuery);

预期结果是javascript在Scribblemap api上调用一个函数来保存地图。

实际结果是未捕获的TypeError:无法读取未定义的属性'map'

1 个答案:

答案 0 :(得分:-1)

由于html元素没有map属性,因此我认为您正在尝试访问此sm

var loadmap = function () {
    var sm = new 
        scribblemaps.ScribbleMap(document.getElementById('ScribbleMap'),
            { controlMode: { 'mapType': scribblemaps.ControlModes.SMALL } }
    );
}

您必须将此sm实例传递给函数,才能使其正常工作。