当我点击一个按钮时,我有一个应该在移动设备上滑出的菜单,但是因为我做了以后添加了菜单和按钮所以它不再有效通过AJAX而不是直接在标记中。
以下是代码:
检查当前屏幕(现在的窗口)大小并调用抓取文件的函数:
var windowWidth = $(window).width(); //Will be screen.width later, using window for testing
if (windowWidth < 550) {
getPhpFile('mobilemenu', '#main-nav-container', 'insertAfter');
getPhpFile('mobmenuimg', '#main-nav-container', 'append');
}
如果成功,此函数会抓取文件并调用将其添加到HTML的函数:
function getPhpFile(filename, selector, method) {
$.ajax({
url : "includes/" + filename + ".php",
type: "POST",
success: function(data, textStatus, jqXHR) {
appendToHtml(data, selector, method);
},
error: function (jqXHR, textStatus, errorThrown){
console.log('Unable to get the requested files.');
}
});
}
将抓取文件中的数据添加到HTML:
function appendToHtml(data, selector, method) {
var element = $('' + selector + '');
switch (method) {
...
//Some removed cases here
...
case 'append': element.append(data);
break;
case 'insertAfter': $(data).insertAfter(element);
break;
}
}
这就是菜单滑出的原因:
$('#mobile-nav-btn').on('click', function() {
if ($('#mobile-nav-container').is(':hidden')) {
$('#mobile-nav-container').stop().show().animate({left: 0}, 'slow');
}
else {
$('#mobile-nav-container').stop().animate({left: -150}, 'slow', function() {
$('#mobile-nav-container').hide();
});
}
});
我已将搜索范围缩小到由于某种原因无法找到#mobile-nav-btn
的事实。这是因为当我使用除按钮之外的其他东西来触发滑动功能时,脚本实际上是有效的。我发现这有点奇怪,因为当我检查控制台时,按钮和菜单实际上是在标记中,并且我不会运行脚本,直到标记出现,因为它是通过点击触发的事件。我尝试使用window.onload = init
作为滑动脚本,但它什么也没做。所有内容都封装在$(document).ready
函数中。我真的坚持如何解决这个问题所以我应该做些什么?
答案 0 :(得分:2)
您正在尝试将事件绑定到不存在的元素。您可以使用事件委派语法在导航按钮的父元素上使用事件委派:
$('parent-element').on('click','#mobile-nav-button', function(){ ....
或者您必须在将这些元素添加到DOM后绑定事件。