下面的代码是一个简单的插件,它向 wooCommerce 产品页面(前端)添加一个新选项卡,然后向该选项卡添加一个按钮。我想要它做的是在单击按钮时弹出警报。这非常简单,我知道,但我创建它是为了尝试弄清楚为什么更复杂的脚本不起作用。
到目前为止,选项卡和按钮都存在,但是当我点击按钮时没有任何反应。我已经检查以确保脚本确实正在加载,并且我已经确认它确实存在于页面的源代码中。如果我直接在浏览器中从源代码加载 javascript 文件路径,它会显示正确的代码。
此外,如果我用 javascript 代码和按钮(所以没有 wordpress 的东西)制作一个简单的 html 文件,它工作得很好。
此外,我在 php 文件的 html 输出中直接添加了一个简单的警报命令,这也可以正常工作。
这让我相信问题与 ID 相关,但我不知道该怎么做。
这是 php 文件(为清楚起见减去插件 header ):
<?php
//runs addScripts
add_action( 'wp_enqueue_scripts', 'addScripts' );
// enqueues jquery and test1.js files. Inspecting html shows these are loaded.test1.js is loaded in footer.
function addScripts(){
wp_enqueue_script( 'jquery', plugins_url( 'jquery.js', __FILE__ ));
wp_enqueue_script( 'test1', plugins_url( 'test1.js', __FILE__ ),array('jquery'),1,true);
}
// creates new tab in woocommerce
add_filter( 'woocommerce_product_tabs', 'woocommerce_product_custom_tab' );
// function defining test_tab
function woocommerce_product_custom_tab($tabs) {
$tabs['test_tab'] = array(
'title' => __( 'New Product Tab', 'woocommerce' ),
'priority' => 50,
'callback' => 'woo_new_product_tab_content'
);
return $tabs;
}
// content of new tab, and where the javascript is supposed to work.
function woo_new_product_tab_content() {
echo <<<END
<button id="mybutton" type="button">Click Me</button>
<script type="text/javascript" src="test1.js"></script>
<script type="text/javascript">
<!--test1();//--></script>
<script type="text/javascript"> alert('ALERT!') </script>
END;
}
?>
这里是包含 javascript 函数的 test1.js:
function test1(){
$( "#mybutton" ).click(function( event ) {
alert ('Hello')
});
}
是否有可能 test1.js 中的#mybutton 没有将函数引导至 php/html 中的“mybutton”按钮?
感谢您的帮助!
更新:我现在有一个在 php echo 中使用以下内容的功能按钮:
<script type="text/javascript">
jQuery(document).ready(function($) {
$( "#mybutton" ).click(function( event ) {
alert ('Hello')});
});
</script>
但以下不起作用:
<script type="text/javascript">
jQuery(document).ready(function($) {
test1(); });
</script>
像以前一样使用 test1.js。
更新 2
因此,虽然下面的答案最终使代码正常工作,但这是一个试验的更复杂的东西失败了。通过执行以下操作,我终于让它工作了(这可能不是最优雅的解决方案):
add_action('wp_head', 'DPG_execute_script');
function DPG_execute_script() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// javascript goes here.
});
</script>
<?php
}
我无法使用 echo <<
最佳答案
如果您在 wordpress 中使用 jQuery 函数,则必须通过以下方式之一使用它:
如果您希望在文档加载后执行您的代码:
jQuery(document).ready(function($) { // Code here will be executed on document ready. Use $ as normal. });
如果您的代码要在匿名函数中执行,请确保将 jQuery 作为参数传递:
(function($) { // Your jQuery code goes here. Use $ as normal. })(jQuery);
编辑: 这就是我实现代码的方式:
<button id="mybutton" type="button">Click Me</button>
<script type="text/javascript">
jQuery("#mybutton").click(function() {
alert ('Hello')
});
</script>
重要:脚本必须在按钮之后调用!
关于javascript - 简单的 Javascript 在 Wordpress/WooCommerce 插件中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522425/