繁体   English   中英

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

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

我有一个选择列表,它具有如下的.topics

  • 国别
    • 美国
    • 英国
  • 科学
    • 物理
    • 化学
  • 健康
  • 历史

并具有输入文本字段,它具有类.body 如果用户写任何被选为topic单词,我想将正文的背景颜色更改为红色。 如何使用jQuery实现此功能? 我尽力解决了这个问题,但是我不知道为什么我的想法没有达到起点。 感谢您给我一个提示,因为我是jQuery新手。

对于刚接触Jquery的人来说,这似乎令人望而生畏,但是如果您在这里熟悉Jquery Docs: 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
            }
        }
    });

});

暂无
暂无

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

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