如何使用jquery检测选中的单词并更改输入字段的背景

How to detect selected word and change the background of input field with jquery

本文关键字:输入 字段 背景 单词 检测 jquery 何使用      更新时间:2023-09-26

我有一个选择列表,它的类别为.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
            }
        }
    });
});