javascript - 获取函数外变量的值
问题描述
我正在使用可排序的 jquery,我正在获取 li 的索引值及其更改属性。我想通过ajax发送索引值和属性值。这是我的代码:
$(function() {
$('ul').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
update: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var li_id = $(li).attr('data-id'), // send this value in ajax call
var end_pos = ui.item.index(); //send this value in ajax call
}
});
});
我想发送这些值是这样的:
$.ajax({
type: "GET",
dataType: "json",
url: `${SiteConfig.staticContentBaseUrl}/sortabletable`,
data: {
id: li_id,
position: end_pos,
_token: $('meta[name=csrf-token]').attr('content')
},
如何访问函数外部的变量值?
解决方案
将这两个功能分开,因为它们实际上是两个不同的工作。
$(function() {
$('ul').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
update: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var li_id = $(li).attr('data-id'), // send this value in ajax call
var end_pos = ui.item.index(); //send this value in ajax call
do_ajax(li_id, end_pos); //do ajax here
}
});
});
function do_ajax(li_id, end_pos) {
$.ajax({
type: "GET",
dataType: "json",
async: true, //I added this for better user experience if nothing else depends on it.
url: `${SiteConfig.staticContentBaseUrl}/sortabletable`,
data: {
id: li_id,
position: end_pos,
_token: $('meta[name=csrf-token]').attr('content')
}
});
}
推荐阅读
- sql - 如何在Access中的查询中添加基于排序值的序列号
- html - 无法覆盖角度 6 中 ng-multiselect-dropdown 中的默认 css 样式
- java - 阅读表时的授权问题
- perl - Cpanm Ansible 与列表
- appium - Appium:无法从 GitHub 检索 Appium 版本 1.9.1 的 git 修订版。原始错误:错误:读取 ECONNRESET
- python-3.x - 蟒蛇 3.6.3。zlib 压缩
- jquery - 多次调用的点击函数
- reactjs - 启用在客户端 spfx 中使用 reactstrap 库
- javascript - 创建一个可点击的时间线图表表单
- javascript - Javascript删除合并某些属性的对象列表中的重复项