传递给wp_enqueue_script时脚本不起作用

时间:2016-04-28 03:50:01

标签: wordpress wordpress-plugin

在意识到我需要对我网站上的任何javascript使用wp_enqueue_script之后,我已经开始尝试使用wp_enqueue_script并且没有得到任何位置。

我的.php文件包含:

<?php
function EnactScript(){
    wp_register_script('CommercePlugin', plugins_url('js/CouponGenerator.js', __FILE__), array('jquery'), '', false);
    wp_enqueue_script('CommercePlugin');
}
add_action('wp_enqueue_scripts', 'EnactScript');
function GenCoupon(){
echo "<input type = \"button\" onclick = \"randomCoupGen(); this.disabled = true\">Click here to see if you won!!</input>";
echo '<imgr src="' . plugins_url('js/CouponGenerator.js', __FILE__) . '" > ';
}
add_filter('woocommerce_before_checkout_form', 'GenCoupon', 9999999, 2);
?>

这是CouponGenerator.js代码:

<html>
<head>
<script type = "text/javascript">
function randomCoupGen()
{
var RanNum = Math.floor(Math.random() * 6);
if(RanNum == 1)
{
alert("You rolled a 1");
}
else if(RanNum == 2)
{
alert("You rolled a 2.");
}
else
{
alert("You rolled something other than 1 or 2");
}
}
</script></head><body></body></html>

在wp_head()时,我需要做些什么来确保我的JS被加载?被称为?

1 个答案:

答案 0 :(得分:0)

你排队剧本的方式没有错。确保JS文件实际存在于指定的路径中。

此外,您可能需要删除<imgr>标记,无论它意味着什么。

最后,您不需要JS文件中的HTML标记。 您的CouponGenerator.js代码应如下所示:

function randomCoupGen()
{
var RanNum = Math.floor(Math.random() * 6);
if(RanNum == 1)
{
alert("You rolled a 1");
}
else if(RanNum == 2)
{
alert("You rolled a 2.");
}
else
{
alert("You rolled something other than 1 or 2");
}
}