简体   繁体   English

移至js文件时,jQuery函数停止工作

[英]JQuery function stops working when moved to js file

I've been developing my scripts in line and now want to start moving them to a js file. 我一直在在线开发脚本,现在想开始将它们移动到js文件中。 However, the first script I am moving will not work from the js file. 但是,我要移动的第一个脚本在js文件中不起作用。

function listEvents(url, phash) {
    var hashlocation = phash.split('#')[1];
    if (hashlocation === undefined) {
        var page = '';
    } else {
        var page = hashlocation;
    }
    $('#events').empty().load(url + page);
} 

Called from page like so; 从页面这样调用;

$(window).load(function() {
    listEvents('<? echo base_url(); ?>ajax/events_ajax/',window.location.hash);
});

The js file is loaded after the jquery library in the head before anyone asks. js文件在任何人要求之前都被加载到头部的jquery库之后。 I have cleared my cache, put cloudflare into dev mode etc, and if I load the JS file in my browser I see my function. 我已经清除了缓存,将cloudflare置于开发模式等,如果在浏览器中加载JS文件,我会看到我的功能。 I'm not seeing any errors in the console. 我没有在控制台中看到任何错误。 What am I missing? 我想念什么?

I suppose that you would need to put your code into .ready function: 我想您需要将代码放入.ready函数中:

$(document).ready(function() {
   $(window).load(function() {
      listEvents('<? echo base_url(); ?>ajax/events_ajax/',window.location.hash);
   });
});


Explanation: 说明:

The problem is that when you fired your code, the content has not fully been loaded, which in your case, I think is #events . 问题是,当您触发代码时,内容尚未完全加载,就您而言,我认为是#events It was not on the DOM yet and as a result ignored by jQuery. 它尚未在DOM上,因此被jQuery忽略。 If you run it in you HTML file, most like you'd put your code right under <div id="events"></div> (or whatever your container is) and because it was executed afterwards, that element was found and your code worked expected way! 如果您在HTML文件中运行它,则最像您将代码放在<div id="events"></div> (或您的容器所处的目录)下一样,并且由于它是在以后执行的,因此可以找到该元素并您的代码按预期方式工作!

Read more about jQuery .ready() function 阅读有关jQuery .ready()函数的更多信息

  • .ready() function: Specify a function to execute when the DOM is fully loaded. .ready() 函数:指定在DOM完全加载时要执行的函数。

My guess is your embedded PHP <? echo base_url(); ?> 我的猜测是您的嵌入式PHP <? echo base_url(); ?> <? echo base_url(); ?> <? echo base_url(); ?> : <? echo base_url(); ?>

listEvents('<? echo base_url(); ?>ajax/events_ajax/',window.location.hash);

Check your network panel in your browser's dev tools, not just console. 在浏览器的开发工具中检查您的网络面板,而不仅仅是控制台。 See if you're seeing any 404s. 查看您是否看到任何404。

If you were working with inline scripts, those are PHP, but after moving to a .js file, the files are no longer handled by PHP. 如果您使用的是内联脚本,则它们是PHP,但是移到.js文件后,这些文件将不再由PHP处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM