全部, 我有以下代码:
$(document).ready(function() {
// more code using $ as alias to jQuery
alert('it works');
},'jQuery');
当页面加载时,我收到以下错误:
Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function
在我尝试添加之前,我已经加载了jQuery。
这是如何加载的(我的代码是custom.js):
<script type='text/javascript' src='http://localhost/oml_live_update/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/plugins/prettyphoto/js/jquery.prettyPhoto.js?ver=3.1.3'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/js/superfish.js?ver=1.4.8'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/js/flexslider.js?ver=1.8'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/js/roundabout.js?ver=1.1'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/assets/js/alyeska.min.js?ver=1.0'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/assets/js/custom.js?ver=1.0'></script>
关于为什么这不起作用的任何想法?
答案 0 :(得分:2)
$(function() {
alert('it works');
});
这不适合你吗?这是此标准语法:http://api.jquery.com/ready/
如果要创建IIFE(立即调用的函数表达式):
(function ($) {
alert('it works');
})(jQuery);
这会为代码创建一个新范围,并将jQuery
对象作为$
传递。
我不使用WordPress,但我的理解是$j=jQuery.noConflict();
运行,所以jQuery基本上存储在$j
变量中(如果它不是自动完成的话则需要手动完成) ):
<script type='text/javascript' src='http://localhost/oml_live_update/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script>
$j = jQuery.noConflict();
$j(function () {
alert('it works');
});
</script>
...
另请注意,您可以将$
传递给document.ready
事件处理程序的匿名函数,这样您就不必使用$j
:
$j(function ($) {
alert('it works');
//you can now use $() instead of $j()
});
您是否尝试使用jQuery
代替$
?
jQuery(function($) {
alert('it works');
//since `$` was passed into this function, it can be used instead of `jQuery`
});
答案 1 :(得分:0)
问题可能是冲突的版本。使用
<script>
$.noConflict();
$(document).ready(function() {
// more code using $ as alias to jQuery
alert('it works');
}); //You dont need to pass the pass the extra 'jQuery' Parameter
</script>