繁体   English   中英

Javascript字数价格计算器

[英]Javascript word count price calculator

一切正常,除了选择定价计划的问题。 我想要的是,只要用户单击指定的价格(即使文本已经存在于textarea中),它都应立即更新最终价格。 但是,第一次单击时不会改变。

我应该点击两次。 有人知道怎么了吗?

所以这里看起来像:

在此处输入图片说明

JavaScript代码如下:

function __textCalculatorCounter(){

    var value = $('#calculateText').val();
    var spanWords = $('#calculatedWordsTotal'),
        spanChars = $('#calculatedCharsTotal'),
        spanPrice = $('#calculatedPriceTotal');


    if (value.length == 0) {
        spanWords.html(0);
        spanChars.html(0);
        return;
    }

    var selectedPricing = $("input[name=calculatePrice]:checked").val();
    var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
    var totalChars = value.length;
    var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));

    spanWords.html(wordCount);
    spanChars.html(totalChars);
    spanPrice.html(totalPrice.toFixed(2));
}

function _initTextCalculator(){
    var textblock = $('#calculateText');
    textblock.change(__textCalculatorCounter);
    textblock.keydown(__textCalculatorCounter);
    textblock.keypress(__textCalculatorCounter);
    textblock.keyup(__textCalculatorCounter);
    textblock.blur(__textCalculatorCounter);
    textblock.focus(__textCalculatorCounter);
    $('label', '#pricesGroup').click(__textCalculatorCounter);
}

====更新====

我不知道为什么,但是它在jsfiddle中可以正常工作...它是从html和javascript中提取的完全相同的代码。

JSFIDDLE

因此,由于没有人回答,我发布了我的答案,该问题得以解决。

问题出在Twitter的Bootstrap 3单选按钮样式中,当与javascript一起使用时,这实际上是常见问题。

我更改了单选按钮的点击处理程序:

function _initTextCalculator(){
    var textblock = $('#calculateText');
    textblock.change(_textCalculatorTrigger);
    textblock.keydown(_textCalculatorTrigger);
    textblock.keypress(_textCalculatorTrigger);
    textblock.keyup(_textCalculatorTrigger);
    textblock.blur(_textCalculatorTrigger);
    textblock.focus(_textCalculatorTrigger);

    // Fixing bootstrap 3 radio buttons
    $("#pricesGroup label").on('click', function(){
        // Once clicked, mark current radio as checked
        $('input:radio', this).prop("checked", true);
        // Then call a function to calculate the price
        _textCalculatorTrigger();
    });
}

正如已经注释过的那样,一旦其父label标签被单击,它将首先为单选按钮分配一个“选中”属性,然后调用一个函数来计算价格。

谢谢大家

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM