简体   繁体   中英

How can I select the first specific class after element in jQuery

I need to count the characters of the content in textarea and show it at the below in a specific class.

I'm using the code below which doesn't work for me:

<script type="text/javascript" charset="utf-8">
    $(document).ready(function(){
        $(".messageText").each(function(){
            $(this).next(".messageCharacters").text($(this).val().length);
            $(this).next(".messagePages").text(($(this).val().length / 70).toFixed());
        });
        $(".messageText").keyup(function(){
            $(this).next(".messageCharacters").text($(this).val().length);
            $(this).next(".messagePages").text(($(this).val().length / 70).toFixed());
        });
    });
</script>

<p>
    <textarea name="title1" class="messageText">phrase1</textarea>
    <br /><span class="messageCharacters">0</span> characters - <span class="messagePages">0</span> pages
</p>
<p>
    <textarea name="title2" class="messageText">phrase2</textarea>
    <br /><span class="messageCharacters">0</span> characters - <span class="messagePages">0</span> pages
</p>

How should I fix it?

The element next to your .messageText is the br , so $(this).next(".messageCharacters") will never return your element.

Use .nextAll() instead :

$(this).nextAll(".messageCharacters")

First of all your $(".messageText").keyup(function(){ is outside the document.ready function, therefore your .messageText element are not collected by the DOM parser.

Also .next() element is <br> so either you need to target a parent container or do a .nextAll() like:

$(function(){  // DOM ready shorthand

  function count() {
    $(this).nextAll(".messageCharacters").text(this.value.length);
    $(this).nextAll(".messagePages").text((this.value.length/70).toFixed());
  }

  $(".messageText").each(count).on("input", count);

});

to prevent one copy-pasteing text inside your textarea (using mouse right click - paste ) and your script doing nothing use .on("input") to register any change inside the textarea value listener.

Also think about ($(this).val().length/70).toFixed() if initially 34 characters makes it pages=2 only at 105 you'll get pages=3 . So review that math again.

jsBin demo

$(this).next更改 $(this).siblings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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