需要帮助来调试jQuery char计数器逻辑 [英] Need help to debug jQuery char counter logic

查看:85
本文介绍了需要帮助来调试jQuery char计数器逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本区域,下面有一个计数器,用于对输入字符进行计数.还设置了最大输入限制.我还添加了一些跨度,当它们被单击时,它们也将值插入到该文本区域中.

I have a textarea with a counter below that counts input characters. There is a maximum input limit set as well. I also added couple of spans that insert values into that textarea too when they are clicked.

<span id="tag1" class="tags"></span>
<span id="tag2" class="tags"></span>
<br>
<textarea id="myTextArea"></textarea> 
<br>
Counter: <font id="charCount"></font>

跨度中的内容包含一个数字值,例如(10).将值插入到textarea中时,我需要使计数器增加该值,而不是增加插入中的字符数.

The content in the spans contains a numeric value, like (10). When the value is inserted into textarea I need the counter to increase by that value and not by the char count in the insert.

当前其中一些有效,而某些无效.需要帮助将其放在一起.我将代码放在这里: http://jsfiddle.net/8R9DH/11/

Currently some of it works and some not. Need help putting it together. I put my code here: http://jsfiddle.net/8R9DH/11/

预期行为:

  1. 直接输入文本或单击跨度或两者结合即可输入文本区域
  2. 计数器对所有字符进行计数,直到达到上限为止,一旦达到限制就停止输入
  3. 计数器对手动输入的每个字符和空格进行计数,但是当用户使用插入内容时,计数器将通过包含中包含的数值增加.例如. <文本包含(5)> == 5或 <文本包含(10)> == 10 例如,以下输入应计为13个字符:

  1. Input into text area can be done via typing in directly or by clicking on of the spans or a combination of both
  2. Counter counts all characters up to a max and stop input once the limit is reached
  3. Counter counts each character and space entered manually but when an insert is user the counter is increased by the numeric value contained in the include. Eg. <text include (5)> == 5 or <text include (10)> == 10 For example, the following input should be counted as 13 characters:

<textarea id="myTextArea">abc <text insert (5)> 123</textarea>

推荐答案

您的JavaScript逻辑中有错误.跨度的名为onClick事件的函数还应该包含正确更新计数的逻辑.下面是它的示例.

There is an error in your javascript logic. Function called onClick event of the span should also include the logic to update the count correctly. Below would be sample for it.

$(".tags").click(function() {
    var insertTag = $(this).text(),
        tagLength = insertTag.replace(/[^0-9]/g, "");
    var n = parseInt(input.val().replace(/{|}/g, '').length) + parseInt(tagLength);
    if ( n <= limit ) {
        input.append(" &lt;" + insertTag + "&gt;");
        count.text( n );
    }
});

但是应该进一步改进此代码,以正确计算文本框中的现有内容.因此

But this code should be further improved to correctly count the existing in the text box correctly. Hence

input.val().replace(/{|}/g, '').length

应该进行改进,以分别过滤掉现有标签,并在文本框中计算其他字符的计数.

should be improved to filter out existing tags separately and calculate the count with other characters in the text box.

这篇关于需要帮助来调试jQuery char计数器逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆