JS/HTML:将类添加到搜索输入的父级不起作用

JS / HTML : Adding class to parent of search input not working

本文关键字:输入 搜索 不起作用 添加 HTML JS      更新时间:2023-09-26

嗨,我正在尝试选择搜索输入的父div,以便在聚焦搜索输入时更改背景颜色。我很困惑为什么这个代码不起作用。谢谢你的帮助。

http://jsfiddle.net/BZ5uf/1/

HTML

<div class="search">  
   <input class="box" value="Search" onfocus="if(this.value=='Search') this.value='';" onblur="(this.value=='') this.value='Search';">
</div>

CSS

.search {
    position: relative;
    margin: 20px; 
    width: 300px;
    height: 65px;
    border: 1px solid black;
}
input.box { 
    margin: 10px;
}
.fill {
    background: #222;
}

JAVASCRIPT

$(function(){
    $('.box').focus(function(){
        $(this).parent().addClass('fill');
 )};

语法错误很多。

)}; //mismatched order

应该是

    });
}); //you also forgot to close DOM ready handler

还可以尝试使用小提琴顶部的"JSHint"按钮。

好的IDE也会为您突出这些错误。使用适当的缩进还有助于找到未关闭的处理程序:

$(function () {
    $('.box').focus(function () {
        $(this).parent().addClass('fill');
    });
});

上面的格式是使用jsfiddle的"整理"按钮获得的。这是你最新的小提琴。

jsFiddle上的工作示例。

$('.box').on('blur', function () {
    $(this).parent()
           .addClass('fill');
});

您的JavaScript:中存在错误

更改此项:

$('.box').focus(function(){
    $(this).parent().addClass('fill');
)};

至:

$('.box').focus(function(){
    $(this).parent().addClass('fill');
});

(注意翻转的大括号顺序)

你的JS中有一个拼写错误,应该是这样的

$(function(){
    $('.box').focus(function(){
         $(this).parent().addClass('fill');
    });
});

看起来有语法错误。这是正确的代码:

$(function(){
    $('.box').focus(function(){
        $(this).parent().addClass('fill');
    });
});

试试这个。

   $(function(){
    $('.box').focus(function(){
        $(this).parent().addClass('fill');
    });
});