从 onclick 函数中获取值并在函数外部使用它
Get value from onclick function and use it outside function
假设我在 jquery 中有这个功能。我正在尝试访问指定元素的 id,然后随意使用。
var values = somejson.json;
$('.get-id').on('click', function () {
var el = $(this);
console.log(el.data('id'));
console.log("====");
var id = el.data('id'); //get this id
});
//i would like to use the id here I retrieve here.
var result = values.find(x => x.id === id);
console.log(result);
我认为这可能很简单,但我无法全神贯注。一些帮助将不胜感激。提前致谢。
有几种方法可以做到这一点。一个是@John 所说的。但是,您可能会污染全局名称空间,具体取决于您声明 id
变量的位置和方式。
另一个很好的方法是将需要 id
值的代码包装在一个函数中。像这样:
var values = somejson.json;
$('.get-id').on('click', function () {
var el = $(this);
console.log(el.data('id'));
console.log("====");
useTheId(el.data('id'));
});
function useTheId(id) {
var result = values.find(x => x.id === id);
console.log(result);
}
重写答案以考虑到问题中添加的额外代码。
您需要做的是:
1. 设置你的地图和你需要的一切一次
2. 每次点击移动标记
所以你的代码应该这样排序:
// setup of map, marker (with default coordinates), etc.
var marker = ...
var map = ...
$('.get-id').on('click', function () {
// do everything you need to do to get the lat lng
var el = ...
var id = ...
var lat = ...
var lng = ...
// move the existing marker to the new position
// you will need to figure out how to do it with your library
// all variables for marker, map, etc. will be accessible here
// or delete the old marker and create a new one, or whatever else works for you
marker.move();
});
假设我在 jquery 中有这个功能。我正在尝试访问指定元素的 id,然后随意使用。
var values = somejson.json;
$('.get-id').on('click', function () {
var el = $(this);
console.log(el.data('id'));
console.log("====");
var id = el.data('id'); //get this id
});
//i would like to use the id here I retrieve here.
var result = values.find(x => x.id === id);
console.log(result);
我认为这可能很简单,但我无法全神贯注。一些帮助将不胜感激。提前致谢。
有几种方法可以做到这一点。一个是@John 所说的。但是,您可能会污染全局名称空间,具体取决于您声明 id
变量的位置和方式。
另一个很好的方法是将需要 id
值的代码包装在一个函数中。像这样:
var values = somejson.json;
$('.get-id').on('click', function () {
var el = $(this);
console.log(el.data('id'));
console.log("====");
useTheId(el.data('id'));
});
function useTheId(id) {
var result = values.find(x => x.id === id);
console.log(result);
}
重写答案以考虑到问题中添加的额外代码。
您需要做的是:
1. 设置你的地图和你需要的一切一次
2. 每次点击移动标记
所以你的代码应该这样排序:
// setup of map, marker (with default coordinates), etc.
var marker = ...
var map = ...
$('.get-id').on('click', function () {
// do everything you need to do to get the lat lng
var el = ...
var id = ...
var lat = ...
var lng = ...
// move the existing marker to the new position
// you will need to figure out how to do it with your library
// all variables for marker, map, etc. will be accessible here
// or delete the old marker and create a new one, or whatever else works for you
marker.move();
});