j查询按键添加类

jquery keypress to add class

本文关键字:添加 查询      更新时间:2023-09-26

我正在尝试学习jquery按键来添加类系统。

我尝试了以下代码,但它不起作用。我在这里尝试过使用 ID。启动#ttt1时,#rb1背景颜色应该会改变,但没有任何反应。

我做错了什么或我需要在这里做什么?谁能告诉我?

这个 id 演示来自 codemep.io

$(document).ready(function() {
   var ID = $(this).attr("id");
   $("#ttt" + ID).on('keypress', function() {
      if ($(this).val().length > 20) {
         $("#rb" + ID).addClass("ad");
      } else {
         $("#rb" + ID).removeClass("ad"); 
      }
   });
});

.HTML

<div class="container">
   <div class="tWrp">
      <textarea class="test" id="ttt1" placeholder="Write"></textarea>
   </div>
   <div class="br" id="rb1">Button</div>
</div>
<div class="container">
   <div class="tWrp">
      <textarea class="test" id="ttt2" placeholder="Write"></textarea>
   </div>
   <div class="br" id="rb2">Button</div>
</div>

您正在定义一个变量ID在函数中,该变量发生在$(document).ready() 上。在该函数中,this的值将指向document。您需要做的是在 keypress 事件处理程序函数中定义变量。

使用类进行选择,然后在处理程序函数中使用$(this).attr("id")。您也可以使用 $(this).closest('div').next() 获取父元素中的下一个元素。

演示

$(document).ready(function() {
   //here  value for this is the document object and the id is not useful.
   $(".test").on('keyup', function() {
     //but here value for this is textarea where keypress event happened.
      var ID = this.id;
      if (this.value.length > 20) {
         $(this).closest('div').next().addClass("ad");
      } else {
         $(this).closest('div').next().removeClass("ad"); 
      }
   });
});
.container {
   margin:0px auto;
   width:100%;
   max-width:500px;
   position:relative;
   margin-top:100px;
}
.test {
   outline:none;
   border:1px solid red;
   width:100%;
   min-height:100px;
}
.br {
   background-color:blue;
   width:100px;
   height:40px;
}
.ad {
   background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
   <div class="tWrp">
      <textarea class="test" id="ttt1" placeholder="Write"></textarea></div>
   <div class="br" id="rb1">Button</div>
</div>
<div class="container">
   <div class="tWrp">
      <textarea class="test" id="ttt2" placeholder="Write"></textarea></div>
   <div class="br" id="rb2">Button</div>
</div>