非常基本的javascript函数调用 [英] Very basic javascript function call

查看:79
本文介绍了非常基本的javascript函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从那以后一直在做传单API。我一直被困在函数调用中,这给了我意想不到的行为。代码如下

I have been doing leaflet API since 2 days. I have been stuck in a function call which gives me unexpected behaviour. the code is as follows

var it=0;

var map = L.map('map1', {
    center:[51.505,-0.09],
    zoom: 2,
});

L.tileLayer('http://{s}.tile.cloudmade.com/c77b2fb7bfb74f74998061abda20d58f/997/256/{z}/{x}/{y}.png',{
    attribution: '2013 &copy @ Rajat/Akshat',
    maxZoom: 18
}).addTo(map);

var marker = L.marker([51.5,-0.09], {draggable: true, opacity: 0.8}).addTo(map);

function onDragEnd(e) {
    var lat_marker = e.target._latlng.lat;
    var lng_marker = e.target._latlng.lng;      
}

var i=6;
marker.on('dragend',onDragEnd(event));

map1 div id已创建于HTML页面。

The map1 div id has been created on HTML page.

现在问题是这个函数:

marker.on('dragend',onDragEnd(event));

显示此错误


ReferenceError:未定义事件

ReferenceError: event is not defined

marker.on('dragend',onDragEnd(event));

marker.on('dragend',onDragEnd(event));

但当我传递它而没有任何参数 marker.on('dragend',onDragEnd()); 时,它的工作原理。

But when I pass it without any argument marker.on('dragend',onDragEnd());, it works.

另外,我想在函数中添加自己的参数:

Also, I want to add my own parameter in the function:

marker.on('dragend',onDragEnd(i));

其中 i 是一个简单的变量。但是这个函数有问题,它没有按预期工作。

Where i is some simple variable. But something is wrong in this function, it doesn't work as expected.

推荐答案

onDragEnd(event)

执行该函数。你只需要传递函数参考

executes the function. You just need to pass in the function reference

marker.on('dragend',onDragEnd);

在函数立即执行函数后使用()。您希望此方法在拖动结束时充当回调。

Using () after the function executes the function immediately. You want this method to act as a callback when the drag ends.

当调用此方法时,事件对象以默认方式传递。所以你不必担心将它作为参数传递

And event object is passed in y default, when this method is invoked. So you need not worry about passing it as an argument

function onDragEnd(event) {

要传递自定义参数,您可以尝试这些行中的内容..

To pass in the custom parameter you can try something in these lines..

for(var i=0; i < $('span').length ; i++) {
    $('span').eq(i).on('click', bindClick(i));
}

function bindClick(index) {
    return function(e) {
        dragEnd(e, index);
    }
}

function dragEnd(e, index) {
    console.log(e);
    console.log(index);
}

代码

for (var i = 0; i < $('.marker').length; i++) {
    var marker = $('.marker').eq(i);
    $('span').eq(i).on('dragend', bindDragEnd(i));
}

function bindDragEnd(index) {
    return function (e) {
        dragEnd(e, index);
    }
}

function dragEnd(e, index) {
    console.log(e);
    // you can access the marker object 
    //by accessing it like $('.marker').eq(index)
}

Check Fiddle

Check Fiddle

这篇关于非常基本的javascript函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆