将jQuery脚本添加到wordpress自定义页面
问题描述:
试图将jQuery脚本合并到Wordpress网站中。将jQuery脚本添加到wordpress自定义页面
我在主题创建一个自定义的页面,并添加body标签下面:
<body>
...
<div id="msgid"> hello there
</div>
...
</body>
我也创建了以下一个test.js文件:
$(document).ready(function(){
$("#msgid").html("Hello world.");
});
我加载test.js在页脚中。
我期待看到Hello world。在div中。但它没有显示任何东西。
任何想法?
谢谢。
答
Wordpress默认使用jQuery的noConflict版本,这意味着它不会将jQuery加载到$符号。
你可以这样做:
jQuery(document).ready(function($){
//inside of here you passed in the $ sign to be used as an alias of jQuery
$("#msgid").html("Hello world.");
});
在这里看到更多细节jQuery的noConflict功能:http://api.jquery.com/jQuery.noConflict/
感谢。我必须使用函数($)还是可以使用函数()并使用jQuery(“#msgid”)而不是$(“#msgid”)?谢谢。 – jdias
@jdias你也可以使用jQuery(“#msgid”)。这里要理解的重要一点是,通过传递$ into函数,实质上是将jQuery分配给$。所以想象这发生了:$ = jQuery。 – kenttam