jQuery.on() 在 WordPress 管理面板中不起作用 [英] jQuery.on() does not work in WordPress admin panel
问题描述
我正在编写自己的 WordPress(4.1.4) 插件,该插件在管理面板中使用了一些 JavaScript 代码.
I'm writing my own WordPress(4.1.4) plugin which uses some JavaScript code in admin panel.
第一个问题是$
对象未定义,所以我用jQuery
代替.
The first issue is $
object is undefined, so I use jQuery
instead.
现在,我想使用 jQuery 处理对 button
的点击:
Now, I want to handle click on the button
using jQuery:
jQuery(function(){
jQuery(".my-button").on("click", function(){
alert("OK");
});
});
不幸的是,这个简单的代码不起作用,但如果我尝试使用它:
Unfortunately, this simple code does not work, but if I try to use this:
jQuery(function(){
jQuery(".my-button").click(function(){
alert("OK");
});
});
效果很好.
一开始还以为是jQuery版本太老了,后来查了一下,发现是1.11.1
.
At first, I thought that jQuery version is too old, but when I checked it, I got 1.11.1
.
所以我不明白为什么 jQuery.on()
在我的情况下不起作用.
So I don't understand why the jQuery.on()
does not work in my case.
推荐答案
通过运行 <?php wp_enqueue_script( $handle, $src, $deps, $版本, $in_footer );?>
,然后将 $in_footer
参数设置为 true.然后 on
函数应该按预期工作.我已经在 WP 版本 4.2.1 中进行了测试,但它应该仍然适用于您的 4.1.4 环境.此代码还允许您使用 $
.
Make sure you code is running at the end of the document by running <?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>
, then setting the $in_footer
argument to true. Then the on
function should work as expected. I've tested in WP version 4.2.1, but it should still work in your 4.1.4 environment. This code will also allow you to use the $
.
(function($){
$(".my-button").on("click", function(e){
e.preventDefault();
alert("OK");
});
}(jQuery));
这篇关于jQuery.on() 在 WordPress 管理面板中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!