Javascript 如何在两个函数中使用相同的私有变量
所以我有两个功能。问题出在Javascript 如何在两个函数中使用相同的私有变量,javascript,jquery,ajax,Javascript,Jquery,Ajax,所以我有两个功能。问题出在styep\u id变量中。我知道我可以在第二个函数中声明它,但他不会从第一个函数中取出数据。所以问题是如何使用相同的变量而不丢失他身上的数据 另外,它不应该是公共变量,因为它不起作用。它不能保存数据 function delete_estimate_position_type() { var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, re
styep\u id
变量中。我知道我可以在第二个函数中声明它,但他不会从第一个函数中取出数据。所以问题是如何使用相同的变量而不丢失他身上的数据
另外,它不应该是公共变量,因为它不起作用。它不能保存数据
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// Ja ir tikko kā pievienots, tad tikai izmetīsim ārā no DOM
if (!styep_id == "") {
estpt_action_links_td_jqobj = $(this).parent();
estpt_tr_jqobj = estpt_action_links_td_jqobj.parent();
stya_id = $("td.service-type-est-position-estimate-position-type-name>input.stya-id-for-styep", estpt_tr_jqobj).val();
estpt_tr_jqobj.remove();
show_stya_delete_link_if_possible(stya_id);
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"));
}
}
及
在第一个函数中调用第二个函数,并将变量作为参数传递:
function delete_estimate_position_type() {
save_configuration(styep_id)
}
function save_configuration(id){
request_url = "/service_type_est_positions/" + id + "/destroy_from_service_type_config";
}
你可以这样用
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
//从争论中得到它
function remove_estpgt_if_has_no_estpt(estpgt_id,styep_id ) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
另一个选项是在隐藏字段中设置它
//html
<input type = "hidden" id="styep_id_newval" value="">
现在,您可以在任何地方轻松访问代码
$("styep_id_newval").val();
您可以在函数调用中传递它。或者另一种方法是,当调用第一个函数时,您可以在隐藏字段中设置值,而在节函数调用中,您可以从隐藏字段中获取值。为什么不正确使用闭包,并在此闭包范围内定义函数和变量?当然,如果你可以选择在哪里定义你的函数。。。否则,除了将其作为参数传递外,没有其他合适的方法。只有一个问题<代码>保存\配置功能只能通过按下“保存”按钮来使用,但现在它的“复制”功能也被
删除\估计\位置\类型
功能按钮使用全局范围变量来检查功能是否执行,但是在保存时,我收到了这个错误-如果我按照你说的那样做-我得到了这种类型的错误-但是我不能使用第二种方法,因为web服务是在Ruby上的,它不是由我创建的,所以有另一种结构。@БццаБааааааааааа。如果没有estpt($(this).attr(“estpgt_id”)、styep_id.val()),则删除estpgt_;你在$(“#styep_id_newval”)(styep_id)中有问题代码>,应该有一个标识符。@БСааБааааааааааа?我还上传了第二个解决方案代码
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
$("#styep_id_newval").(styep_id.val());
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
$("styep_id_newval").val();