【问题标题】:Javascript and JQuery issue with WordpressWordpress 的 Javascript 和 JQuery 问题
【发布时间】:2019-03-20 23:20:25
【问题描述】:

我正在开发一个网站,并且想做一些超出我想象的高级工作(至少对我而言)。我的 JavaScript 知识非常有限,需要帮助。

我有一个 html 表单,它接受 5 个标记为 1-5 的文本输入字段,代表百分比分布。我想使用 javascript 来执行以下操作:

  1. 读取所有字段并确保总和等于 100。
  2. 当总和等于 100 时禁用不必要的字段。
  3. 如果总和不是 100%,则禁用提交按钮。
  4. 在用户条目的末尾添加 %。

我找到了两个单独的脚本来完成这一切,一个是 javascript,另一个是 JQuery。由于某种原因,JQuery 无法正常工作,并产生以下错误:

未捕获的类型错误:$ 不是函数

我已经尝试修改JQuery代码,如在线多个解决方案中的建议,如下所示:

(function($){ "这里是 jQuery 代码" })(jQuery);

这消除了错误,但是 JQuery 代码不起作用。

javascript.js 和 JQuery.js 文件都在 WP 主题的 functions.php 文件中正确排队。

任何帮助将不胜感激!

HTML

<label for="entryFee">Entry Fee:</label>
<input id="entryFee" name="entry_fee" onblur="this.value = '$' + formatNumber(this.value, 1, 2, true)" type="text" value="" placeholder="$100.00" /> &nbsp;
<h4>Prize Distribution</h4>

<label for="1stPlace">1st Place:</label> <input id="1stPlace" name="1st_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="60%" maxlength="3" size="4" class="percentageField" required />

<label for="2ndPlace">2nd Place:</label> <input id="2ndPlace" name="2nd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="30%" maxlength="3" size="4" class="percentageField" />

<label for="3rdPlace">3rd Place:</label> <input id="3rdPlace" name="3rd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="10%" maxlength="3" size="4" class="percentageField" />

<label for="4thPlace">4th Place:</label> <input id="4thPlace" name="4th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />

<label for="5thPlace">5th Place:</label> <input id="5thPlace" name="5th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />

<span id="percent">0</span>%


<input id="submitButton" type="submit" value="Submit" disabled>

</form>

Javascript

// Reformats a number by inserting commas and padding out the number of digits
// and decimal places.
//
// Parameters:
//     number:        The number to format. All non-numeric characters are
//                    stripped out first.
//     digits:        The minimum number of digits to the left of the decimal
//                    point. The extra places are padded with zeros.
//     decimalPlaces: The number of places after the decimal point, or zero to
//                    omit the decimal point.
//     withCommas:    True to insert commas every 3 places, false to omit them.


function formatNumber(number, digits, decimalPlaces, withCommas)
{
        number       = number.toString();
    var simpleNumber = '';

    // Strips out the dollar sign and commas.
    for (var i = 0; i < number.length; ++i)
    {
        if ("0123456789.".indexOf(number.charAt(i)) >= 0)
            simpleNumber += number.charAt(i);
    }

    number = parseFloat(simpleNumber);

    if (isNaN(number))      number     = 0;
    if (withCommas == null) withCommas = false;
    if (digits     == 0)    digits     = 1;

    var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number));
    var string      = "";

    for (var i = 0; i < digits || integerPart > 0; ++i)
    {
        // Insert a comma every three digits.
        if (withCommas && string.match(/^\d\d\d/))
            string = "," + string;

        string      = (integerPart % 10) + string;
        integerPart = Math.floor(integerPart / 10);
    }

    if (decimalPlaces > 0)
    {
        number -= Math.floor(number);
        number *= Math.pow(10, decimalPlaces);

        string += "." + formatNumber(number, decimalPlaces, 0);
    }

    return string;
}

JQuery

(function($){
$('.percentageField').keyup( function () {
    //limit the value to between 0 and 100
    var thisVal = parseInt($(this).val(), 10);
    if (!isNaN(thisVal)) {
        thisVal = Math.max(0, Math.min(100, thisVal));
        $(this).val(thisVal);
    }
    
    //get total of values
    var total = 0; 
    $('.percentageField').each(function() {
        var thisVal = parseInt($(this).val(), 10);
        if (!isNaN(thisVal))
            total += thisVal;
    });
    
    //change the value of the current entry to limit sum to 100
    if (total > 100) {
        $(this).val(thisVal - (total - 100));
        total = 100;
    }
    
    
    if (total == 100) {
        //enable submit button
        $('#submit_button').removeAttr('disabled');
        
        //disable empty input fields
        $('.percentageField').each(function() {
            var thisVal = parseInt($(this).val(), 10);
            if (isNaN(parseInt($(this).val(), 10)) || thisVal == 0)
                $(this).attr('disabled','disabled'); 
        });
    }
    else {
        //disable submit button
        $('#submitButton').attr('disabled','disabled');
        
        //enable all input fields
        $('.percentageField').removeAttr('disabled');
    }
    
    //update percentage
    $('#percent').html(total);
});
})(jQuery);

【问题讨论】:

  • 你先加载jquery库了吗?
  • @Talha,库按以下顺序加载:jquery.js、jquery-migrate.min.js、my-javascript-code.js 和 my-jquery-code.js跨度>
  • @tshimkus,我不确定我是如何复制自调用的。如果不将它添加到我的 JQuery 文件中,我会收到错误“未捕获的 TypeError:$ 不是函数”。如果它被复制,当我从我的文件中删除它时,我不会给我错误,对吧?

标签: javascript jquery wordpress forms


【解决方案1】:

在 DOM 准备好之前,JQuery 脚本正在运行。 将整个代码集包含在 $('document').ready(function() 中就可以了:

(function($){
$('document').ready(function()
   { <<JQuery Code>> });
})(jQuery);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多