简体   繁体   中英

How to make js work with specific html blocks?

I have the following js code

$(function () {
 "use strict";

var maxText = $("textarea").attr("maxlength"),
    
    ourMessage = $(".message");

ourMessage.html('<span>' + maxText + '</span> Characters Remaining');

$("textarea").keydown(function () {
   
    var textLength = $(this).val().length,
        
        remText = maxText - textLength;
    
    ourMessage.html('<span>' + remText + '</span> Characters Remaining');
    
});


 $("textarea").keyup(function () {
   
    var textLength = $(this).val().length,
        
        remText = maxText - textLength;
    
    ourMessage.html('<span>' + remText + '</span> Characters Remaining');
    
}); });

and the following html code snippet:

    <div class="form-group">
        <textarea id="field" placeholder="Type Here" maxlength="3000" rows="10" cols="40"></textarea>
        <div class="message"></div>
    </div>

and it works fine. But I need more than one of html snippets on the same page and I don't know how to change the code so <div class="message"></div> only changes when "it's" textarea is used.

Assuming the div is always directly after the textarea, you can simply call the next method on the textarea to get the div.

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