【发布时间】:2013-12-11 14:59:12
【问题描述】:
下面的代码是一个简单的插件,它向 wooCommerce 产品页面(前端)添加一个新选项卡,然后向该选项卡添加一个按钮。我想要它做的是在单击按钮时弹出一个警报。我知道,这非常简单,但我创建它是为了尝试找出更复杂的脚本无法正常工作的原因。
到目前为止,选项卡存在,按钮存在,但是当我单击按钮时没有任何反应。我已经检查以确保脚本实际上正在加载,并且我已经确认它确实存在于页面的源代码中。如果我直接在浏览器中从源代码加载 javascript 文件路径,它会显示正确的代码。
此外,如果我用 javascript 代码和按钮制作一个简单的 html 文件(所以没有任何 wordpress 的东西)它工作得很好。
此外,我在 php 文件中的 html 输出中直接添加了一个简单的警报命令,这也可以正常工作。
这让我相信问题与 ID 有关,但我不知道该怎么做。
这是 php 文件(为了清楚起见,减去插件标题):
<?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
【问题讨论】:
标签: javascript php jquery wordpress woocommerce