简体   繁体   English

如何使我的jQuery代码更高效?

[英]How can I make my jQuery codes more efficient?

I have the following jquery lines to count how many characters left on 4 different textarea fields: 我有以下jquery行来计算4个不同textarea字段剩余的字符数:

$(window).load(function () {

    $('#submission1').keyup(function() {
        var len = this.value.length;
        if (len >=1500) {
            this.value = this.value.substring(0, 1500);
        }
        $('#countCharacters1').text(1500 - len);
    });
    $('#submission2').keyup(function() {
        var len = this.value.length;
        if (len >=1500) {
            this.value = this.value.substring(0, 1500);
        }
        $('#countCharacters2').text(1500 - len);
    });
    $('#submission3').keyup(function() {
        var len = this.value.length;
        if (len >=1500) {
            this.value = this.value.substring(0, 1500);
        }
        $('#countCharacters3').text(1500 - len);
    });
    $('#submission4').keyup(function() {
        var len = this.value.length;
        if (len >=1500) {
            this.value = this.value.substring(0, 1500);
        }
        $('#countCharacters4').text(1500 - len);
    });
});

They work fine, but is there anyway to make them more efficient? 它们工作正常,但是反正是为了使它们更有效率?

Cheers. 干杯。

Yes, 是,

function countChars(index){
    var len = this.value.length;
    if (len >=1500) {
        this.value = this.value.substring(0, 1500);
    }
    $('#countCharacters' + index).text(1500 - len);
}

$(window).load(function () {

    $('#submission1').keyup(function() {
        countChars.call(this, 1);
    });
    $('#submission2').keyup(function() {
        countChars.call(this, 2);
    });
    $('#submission3').keyup(function() {
        countChars.call(this, 3);
    });
    $('#submission4').keyup(function() {
        countChars.call(this, 4);
    });
});

How about this? 这个怎么样?

$(window).load(function () {
    $('#submission1, #submission2, #submission3, #submission4').keyup(function() {
        var len = $(this).val().length;
        if (len > 1500) {
            $(this).val($(this).val().substring(0, 1500));
        }
        $('#countCharacters' + $(this).attr('id').slice(-1)).text(1500 - len);
    }).keyup();
});

It can be simplified even more if you have a common class across your textareas, and we can avoid the id manipulation at the end of you give us a bit more details about the HTML layout - specifically how the #countCharacters elements are positioned in the DOM relative to the textareas. 如果你的textareas中有一个共同的类,它可以简化得更多,我们可以避免你在结尾处的id操作给我们更多关于HTML布局的细节 - 特别是#countCharacters元素在DOM中的位置相对于textareas。

An ideal solution would look something like this: 一个理想的解决方案看起来像这样:

$(window).load(function () {
    $('.editors').keyup(function() {
        var len = $(this).val().length;
        if (len > 1500) {
            $(this).val($(this).val().substring(0, 1500));
        }
        $(this).next('.count').text(1500 - len);
    }).keyup();
});

This requires your textareas to have the editors class, and the count elements to have the count class and be positioned immediately after their respective textareas. 这要求您的textareas具有editors类,并且count元素具有count类并且紧接在它们各自的textareas之后定位。 A similar solution could be designed regardless of where the count elements are actually positioned though. 无论计数元素实际位于何处,都可以设计类似的解决方案。

Update 更新

Based on this HTML, which you included in a comment: 基于此HTML,您在评论中包含:

<div class="field">
    <textarea name="submission1" class="editors" id="submission1" style="width: 680px"><?=$writtenSubmission1;?></textarea>
</div>
<p align="right">
    <span id="countCharacters1" class="count" style="font-weight:bold">1500</span>
    characters left
</p>

The text() line needs to change to this: text()行需要更改为:

$(this).closest('.field').next().find('.count').text(1500 - len);

Basically, you're just traversing the DOM tree to get from the textarea element $(this) to the correct .count element. 基本上,你只是遍历DOM树,从textarea元素$(this)到正确的.count元素。 See the jQuery docs for more information on functions that are available to help you move around the DOM. 有关可用于帮助您在DOM中移动的函数的更多信息,请参阅jQuery文档

I also made one more minor change above, to trigger the keyup() function immediately after binding the event handler to it, in order to show the correct count as soon as the page loads. 我还在上面做了一个小改动,在将事件处理程序绑定到它之后立即触发keyup()函数,以便在页面加载后立即显示正确的计数。

You can see a working version with your HTML in this fiddle: http://jsfiddle.net/tXArh/ 您可以在这个小提琴中看到HTML的工作版本: http//jsfiddle.net/tXArh/

give class 'text-area' to each textarea then, 然后,给每个textarea提供课程'text-area',

$(window).load(function () {

    $('.text-area').keyup(function() {
        var index = $(this).attr('alt');
        var len = $(this).val().length;
        if (len >=1500) {
            $(this).val($(this).val().substring(0, 1500));
        }
        $('#countCharacters' + index).text(1500 - len);
    });

});

give first textareas alt='1' and like wise 给第一个textareas alt ='1'并且明智一样

Give each of the textareas a common css class (eg submission ). 给每个textareas一个共同的css类(例如submission )。 Then use data-attributes on the textareas, to specify the max. 然后在textareas上使用数据属性来指定最大值。 number of characters allowed and the id of the element, which shows the number of remaining characters: 允许的字符数和元素的id,显示剩余字符数:

<textarea id="submission1"
  class="submission"
  data-maxchars="1500"
  data-remaining="remaining1">
</textarea>
<span id="remaining1"></span> chars left.

This allows you to simplify and generalize your jquery code like this: 这允许您简化和概括您的jquery代码,如下所示:

$(window).load(function(){
    $('.submission').keyup(function() {
        var $ta = $(this);
        var max = $ta.data('maxchars');
        var len = $ta.val().length;
        if (len >= max) {
            $ta.val($ta.val().substring(0, max));
            len = max;
        }
        $('#' + $(this).data('remaining')).text(max - len);
    });
});

Have a look at this jsfiddle for a working example. 看看这个jsfiddle的工作示例。

I think you can use the JQuery each function : 我想你可以使用JQuery的每个功能:

     $.each( [1,2,3,4], function(i, n){  // i = position, n = value
       $('#submission'+n).keyup(function() {
        var len = this.value.length;
        if (len >=1500) {
            this.value = this.value.substring(0, 1500);
        }
        $('#countCharacters'+n).text(1500 - len);
       });
    });  

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

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