简体   繁体   English

如何使 js 与特定的 html 块一起工作?

[英]How to make js work with specific html blocks?

I have the following js code我有以下js代码

$(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:以及以下 html 代码片段:

    <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.但是我在同一页面上需要不止一个 html 片段,而且我不知道如何更改代码,因此<div class="message"></div>仅在使用“它的” textarea时才会更改。

Assuming the div is always directly after the textarea, you can simply call the next method on the textarea to get the div.假设 div 总是直接在 textarea 之后,您可以简单地调用 textarea 上的next方法来获取 div。

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

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