Undefined不是一个函数:jQuery和WordPress

时间:2015-02-24 16:35:42

标签: jquery wordpress

我被困住了。我已经成功使用了WordPress之外的以下代码段,已经确保jQuery正在加载,但我仍然得到'意外令牌=' 。我试过删除' $'从' $ form',然后我得到' undefined不是函数' 。有人可以解释我错过了什么吗?

<head>
  //added via wp_enqueue
  <script type='text/javascript' src='/wp-includes/js/jquery/jquery.js?ver=1.11.1'></script>
</head>
<body>
...
<form id="testForm" action="process-page.php" method="post">
  <input type="submit" id="formSubmit" value="&nbsp;" />
</form>

<script>
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function($) {
    $(this).on('submit',function(e) {
        var $form = $(this);
        if ($form.data('submitted') === true) {
          // Previously submitted - don't submit again
          e.preventDefault();
        } else {
          // Mark it so that the next submit can be ignored
          $form.data('submitted', true);
        }
    });
    // Keep chainability
    return this;
};

jQuery(document).ready(function($) {
    $('form').preventDoubleSubmission();
});
</script>
</body>

2 个答案:

答案 0 :(得分:1)

只需将自定义jQuery函数放在document ready块中,这样就可以使用$。像这样:

jQuery(document).ready(function($) {

    $.fn.preventDoubleSubmission = function() {
        $(this).on('submit',function(e) {
            var $form = $(this);
            if ($form.data('submitted') === true) {
              // Previously submitted - don't submit again
              e.preventDefault();
            } else {
              // Mark it so that the next submit can be ignored
              $form.data('submitted', true);
            }
        });
        // Keep chainability
        return this;
    };

    $('form').preventDoubleSubmission();

});

答案 1 :(得分:-1)

jQuery.fn.preventDoubleSubmission = function() {

应该是

jQuery.fn.preventDoubleSubmission = function($) {

依吾。

你也不应该像这样包含jquery.js,而是使用enqeue。 (<?php wp_enqueue_script('jquery');?>)。