页面上的Wordpress嵌入式JavaScript无效

时间:2015-07-22 09:03:55

标签: javascript jquery html wordpress

我正在尝试复制以下JSFiddle: https://jsfiddle.net/7nbr6/10/

在我的WordPress网站上。

当我将其复制到网站上时,单击按钮时它不会执行任何操作。

我正在使用此插件将javascript放到我的页面上: https://wordpress.org/plugins/css-javascript-toolbox/

HTML:

<!-- Throw in a nice looking font just for the fun of it -->
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,700,300,200">
<div id="wrap">
<h2>Kelly calculator</h2>
    <div class="formStyles"> 
        <input id="probability" type="text" value="Probability"><br>
        <input id="odds" type="text" value="Odds"><br>
        <input id="balance" type="text" value="Balance"><br>
        <input id="submit" type="submit" value="Submit">
        <input id="reset" type="reset" value="Reset">
        <div id="result"></div>
    </div>
</div>

使用Javascript:

<script type="text/javascript">
jQuery('#submit').on('click', function() {
    var probability = jQuery('#probability').val();
    var odds = jQuery('#odds').val();
    var balance = jQuery('#balance').val();
    result = parseFloat(((probability/100)* (odds - 1) / (odds - 1) * odds - 1).toFixed(4)) * 0.95;
    var stake = ((balance / 100) * parseFloat((result * 100).toFixed(2)))
    jQuery('#result').text((result * 100).toFixed(2) + '% of' + balance + '€ which is ' +stake + '€');
});
</script>

代码肯定嵌入到页眉中(通过查看页面源可见),但按钮不起作用。

我最初认为这是noConflict()的问题,详情如下: TypeError: $ is not a function when calling jQuery function

我在编辑器中(插件内部)也有此错误,但在导航到页面时它不会出现在控制台中:

https://i.imgur.com/3FKt1Mi.png

我尝试删除脚本标记,但它只是将其作为文本放入标题中。

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

在DOM准备好之前,您尝试将处理程序附加到元素。将代码包装在ready处理程序中可以解决此问题:

jQuery(function() {
    jQuery('#submit').on('click', function() {
        var probability = jQuery('#probability').val();
        var odds = jQuery('#odds').val();
        var balance = jQuery('#balance').val();
        result = parseFloat(((probability/100)* (odds - 1) / (odds - 1) * odds - 1).toFixed(4)) * 0.95;
        var stake = ((balance / 100) * parseFloat((result * 100).toFixed(2)))
        jQuery('#result').text((result * 100).toFixed(2) + '% of' + balance + '€ which is ' +stake + '€');
    });
});

围绕JavaScript编写的代码是jQuery&#39; .ready事件的简写。

答案 1 :(得分:1)

加载代码时,jQuery还没有准备好。因此,你的代码完全被忽略了。

将您的代码放入:

jQuery(function() {
/* your code here */
)};