如何使用jquery检测选中的单词并更改输入字段的背景
How to detect selected word and change the background of input field with jquery
我有一个选择列表,它的类别为.topics
,如下所示
- 国家
- 美国 英国
- 科学
- 物理学化学
- 健康
并有一个输入文本字段,它有.body
类。如果用户写的任何字被选择为topic
比我想改变主体的背景颜色为红色。我如何用jQuery实现这个东西?我尽了最大的努力去解决它,但我不知道为什么我的思想没有回到起点。谢谢你给我一个提示,因为我是jQuery新手。
对于刚接触Jquery的人来说,这似乎令人生畏,但如果您熟悉了这里的Jquery文档:http://api.jquery.com/,您会发现Jquery是最容易学习的语言之一,并且您可以在短短几个月内很好地处理它。
这里有一个关于你的问题的注释解决方案,我希望它能帮助你理解一点Jquery是如何工作的。一开始可能会让你感到困惑,但是如果你读了足够多的匿名函数和回调,你就会很快理解它。
$(function(){ //this is a shortcut to document ready function
var selected = null;//first, we need to define a variable called selected.
//when the val() of .topics changes,
//this will house the text value of the currently selected option.
$(document).on('change','.topics',function(){
//detect a change in the document only relative to the
//.topics class, according to another post,
//this works with dynamically generated dom elements.
selected = $('.topics').val();//set the value of selected in global
//scope so we can use it in our body keyup
});
$('.body').keyup(function(){ //detect when a user is typing in the .body element(s)
if($(this).val() == selected) //if the value of the element equals the same as the select option
{
$(this).css('background-color','red');//make the background red.
}else{
if($(this).css('background-color') == 'red'){
$(this).css('background-color','');//fall back to default
}
}
});
});
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- 如何在HTML输入字段中添加不可删除的后缀
- 互斥单选按钮和相应的输入字段
- 在IE9中的输入字段中输入焦点最近按钮
- 选中单选框时将属性添加到输入字段
- 当设置addFromAutocompleteOnly时,剩余文本将保留在输入字段中
- 我如何在数字插入中使用逗号,这样它就不会'不要破坏我的输入字段
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 输入字段将't获取更新的值
- 如何选择多个输入字段并删除所需的属性
- 输入字段,只接受0到12之间的数字
- 单击鼠标,用MySQL数据填充html表单输入字段
- 使用jquery将输入字段转换为文本
- Model中的Typeahead返回空值以形成输入字段
- 如何从查询字符串中的输入字段发回文本
- 如何验证日期、月份和日期的3个独立输入字段;年使用jquery或javascript
- 将值传递给jquery创建的输入字段