j查询按键添加类
jquery keypress to add class
我正在尝试学习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>
相关文章:
- 将数据库中的超链接添加到查询结果
- 我想将查询字符串变量添加到JSON名称/值对中
- 新手查询动态添加属性
- 用于添加边缘的gremlin服务器查询
- 添加行并运行多个mySQL查询
- iron路由器将参数添加到字符串中,并添加一个查询
- j查询检查复选框是否被选中,然后向输入字段添加值
- 将查询字符串添加到当前URL中嵌入的查询的锚链接
- 在聚合附近,添加基本查询选项
- jQuery脚本,它搜索现有的查询参数并且不添加“"如果存在
- jasmine:在url中添加和读取查询字符串
- 向Titanium添加查询
- 循环遍历数组,并在javascript中向sql查询添加参数
- 如何在Node.js中向Post请求添加查询
- 动态添加数据时按数据属性查询JQuery选择器
- 向URL重定向添加查询字符串
- 使用pushstate添加查询字符串
- 向data-href中添加查询字符串
- 如何在JavaScript中添加查询字符串
- 使用猫鼬模型添加查询条件