我的代码存在问题,导致它看不到我的函数,即使它在那里。
这是我正在使用的代码:
if (markerNodes.length > 0) {
$("#locationInformation").html('<button align="center" class="btn-orange"' +
'style="margin-right: 50px;" id="closeInfo" onclick="closeInfoBox();">' +
'SEARCH AGAIN</button>');
} else {
alert('Sorry, there are no stores that close to your location.' +
'Try expanding your search radius.');
}
如您所见,我正在将该按钮动态添加到 html div id locationInformation 中。
在同一个 .JS 文件中,我有这个函数,说它找不到:
(function ($) {
....[lots of code here]...
function searchLocationsNear(center) {
....[lots of code here]...
if (markerNodes.length > 0) {
$("#locationInformation").html('<button align="center" class="btn-orange"' +
'style="margin-right: 50px;" id="closeInfo" onclick="closeInfoBox();">' +
'SEARCH AGAIN</button>');
} else {
alert('Sorry, there are no stores that close to your location.' +
'Try expanding your search radius.');
}
....[lots of code here]...
}
....[lots of code here]...
function closeInfoBox() {
if (hasSearched == true) {
hasSearched = false;
$("#addressInput").val('');
clearLocations();
$('.radiusDropDown').val('30');
$('#addressInput').focus();
}
if (hasDirections == true) {
slideDirections("yes");
hasDirections = false;
}
}
....[lots of code here]...
}(jQuery));
所以 .JS 文件看起来像这样(省略不需要显示的代码):
(function ($) {
....[lots of code here]...
function searchLocationsNear(center) {
....[lots of code here]...
if (markerNodes.length > 0) {
$("#locationInformation").html('<button align="center" class="btn-orange"' +
'style="margin-right: 50px;" id="closeInfo" onclick="closeInfoBox();">' +
'SEARCH AGAIN</button>');
} else {
alert('Sorry, there are no stores that close to your location.' +
'Try expanding your search radius.');
}
....[lots of code here]...
}
....[lots of code here]...
function closeInfoBox() {
if (hasSearched == true) {
hasSearched = false;
$("#addressInput").val('');
clearLocations();
$('.radiusDropDown').val('30');
$('#addressInput').focus();
}
if (hasDirections == true) {
slideDirections("yes");
hasDirections = false;
}
}
}(jQuery));
最佳答案
您的函数是在您的 $( )
就绪处理程序内部定义的,因此作为全局函数不可见。
确实没有充分的理由使用内联事件处理程序创建元素:
$("#locationInformation")
.empty()
.append($("<button/>", {
"class": "btn-orange",
"css": { "margin-right": "50px" }, //Needed ":"
"id": "closeInfo",
"click": closeInfoBox,
"text": "SEARCH AGAIN"
}));
或者,您可以只设置一个全局委托(delegate)处理程序,而不是每次附加按钮时都分配事件处理程序。您只需执行一次:
$(document).on("click", ".btn-orange", closeInfoBox);
无论添加和删除按钮多少次,该按钮都将保持有效。
关于JavaScript 未捕获引用错误 : closeInfoBox is not defined (when it really is),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28070999/