简体   繁体   English

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

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

I have a select list, it has class .topics as follows 我有一个选择列表,它具有如下的.topics

  • Countries 国别
    • United States of America 美国
    • United Kingdom 英国
  • Science 科学
    • Physics 物理
    • Chemistry 化学
  • Health 健康
  • History 历史

and have an input text field, it has class .body . 并具有输入文本字段,它具有类.body if user write any word which is selected as topic than i want to change the background color of the body to red. 如果用户写任何被选为topic单词,我想将正文的背景颜色更改为红色。 How do i achieve this thing with jQuery? 如何使用jQuery实现此功能? I tried my best to solve it but i don't know why my mind wasn't getting to starting point. 我尽力解决了这个问题,但是我不知道为什么我的想法没有达到起点。 Thanks for giving me a hint as i am new to jQuery. 感谢您给我一个提示,因为我是jQuery新手。

For someone who is new to Jquery it can seem daunting, but if you familiarize yourself with the Jquery Docs here: http://api.jquery.com/ you will find that Jquery is one of the easiest languages to ever learn, and you can get a good handle on it in as little as a few months. 对于刚接触Jquery的人来说,这似乎令人望而生畏,但是如果您在这里熟悉Jquery Docs: http : //api.jquery.com/您会发现Jquery是有史以来最容易学习的语言之一,并且您短短几个月内就可以很好地处理它。

here is a commented solution to your question, and i hope that it helps you understand a bit how Jquery works. 这是对您的问题的评论解决方案,我希望它可以帮助您了解Jquery的工作原理。 it will seem confusing at first, but if you read enough about anonymous functions and callbacks, you will pick it up in no time. 乍一看似乎很令人困惑,但是如果您对匿名函数和回调有足够的了解,那么您会很快发现它。

$(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
            }
        }
    });

});

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

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