我使用jquery、bootstrap和handlers。当我点击一个选项卡时,我会调用一些函数。在这些函数中,我使用了一些变量
<script>
$(document).ready(function () {
var sourceLodgerContactAvailable = $("#lodger-contact-available-result-template").html();
var templateLodgerContactAvailable = Handlebars.compile(sourceLodgerContactAvailable);
$("a[href='#lodgerContactTab']").on('shown.bs.tab', function (e) {
e.target; // newly activated tab
e.relatedTarget; // previous active tabF
var location = assignLocationToLocal();
$.when(location).then(function () {
getNotAssociateContact();
getAssociateContact();
});
});
);
function getNotAssociateContact() {
$.ajax({
type: "GET",
url: "http://localhost:8080/rest/contacts/notassociatedto/" + $("#lodgerId").val(),
success: function (data, status, jqXHR) {
$("#lodgerContactAvailableDivTemplate").empty();
if (data.length != 0) {
$("#lodgerContactAvailableDivTemplate").append(templateLodgerContactAvailable(data)); //error
$('#lodgerContactAvailableTableResult').bootstrapTable('resetView');
}
},
error: function (jqXHR, status) {
check401Unauthorized(jqXHR);
}
});
}
</script>
我收到这个错误消息。
templateRodgerContactAvailable未定义
这就像函数中未知数中的var。
我需要准备好文档中的功能吗?
尝试从函数传递变量
$.when(location).then(function () {
getNotAssociateContact(templateLodgerContactAvailable);
getAssociateContact();
});
function getNotAssociateContact(templateLodgerContactAvailable) {
//your logic goes here
}
或者在document.ready函数外部声明变量
变量被设置为其函数范围和任何子范围。
function aFunction() {
var a = 12;
}
function bFunction() {
// This won't work because `a` is defined in `aFunction`
console.log(a);
}
var c = 12;
function cFunction() {
// Works because `c` is declared outside of this function
console.log(c);
}
function dFunction() {
// Works for the same reason as `cFunction`
console.log(c);
}
因此,如果您想在两个位置都使用该变量,您应该在$(document).ready
的外部声明它,然后在$(document).ready
内部分配它的值
var templateLodgerContactAvailable;
$(document).ready(function() {
var sourceLodgerContactAvailable = $("#lodger-contact-available-result-template").html();
templateLodgerContactAvailable = Handlebars.compile(sourceLodgerContactAvailable);
...
});
一个更好的方法是让getNotAssociateContact
取一个参数。然后可以将该变量传递给getNotAssociateContact
。
function getNotAssociateContact(template) {
// Use `template` instead of `templateLodgerContactAvailable` inside of this function
...
}
然后,当你想调用函数时,只需将值传递给它
var sourceLodgerContactAvailable = $("#lodger-contact-available-result-template").html();
var templateLodgerContactAvailable = Handlebars.compile(sourceLodgerContactAvailable);
$("a[href='#lodgerContactTab']").on('shown.bs.tab', function (e) {
e.target; // newly activated tab
e.relatedTarget; // previous active tabF
var location = assignLocationToLocal();
$.when(location).then(function() {
getNotAssociateContact(templateLodgerContactAvailable);
getAssociateContact();
});
});