0

我想让 div 背景颜色只有在输入字段中有文本并且没有文本时颜色不会改变或恢复为原始颜色时才会改变颜色。到目前为止,这是我的代码,但它不起作用。

<script type="text/javascript">
    $(document).ready(function () {
        $('#inputDatabaseName').change(function () { 
            $(this).parent().find('#colorchange').css('background-color','#ff0000');
            $(this).css('background-color','#ff0000');
    });
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="colorchange">
        <input id="inputDatabaseName">
        <table id="searchResults"><tr><td>empty</td></tr></table>
    </div>
    </form>
</body>
4

3 回答 3

0

我建议使用类而不是更改 CSS 属性。这应该工作

$(function () {
    $('#inputDatabaseName').keypress(function () { 
        var $this = $(this),
            $div = $(this).parent(); // Cache the jQuery selectors to make code faster
        if ($this.val().length > 0) {
            $div.addClass("hasContent");
        } else {
            $div.removeClass("hasContent");
        }
    });
});

现在添加一些 CSS:

#colorchange { background-color: white } /* default color */
#colorchange.hasContent { background-color: red } /* updated color */
#colorchange #inputDatabaseName { background-color: white } /* default color */
#colorchange.hasContent #inputDatabaseName { background-color: red } /*updated color*/
于 2013-08-01T19:24:51.703 回答
0

您似乎瞄准了错误的元素

你的选择器应该是

$(this).parent('#colorchange')

$(this).parent()指着div id="colorchange">

而你正试图再次找到将搜索它的孩子

如果您希望立即反映更改,请使用keyupevent 而不是。change

ID应该在页面上是唯一的。

应该这样$('#colorchange').css( 做。

$(document).ready(function () {
    $('#inputDatabaseName').keyup(function () {
        var $this = $(this);
        $colorDiv = $('#colorchange');
        defaultColor = 'initial';
        // If value is not empty assign a color
        // otherwise this will be set to default.
        if ($this.val() !== '') {
            defaultColor = '#ff0000';
        }
        $('#colorchange').css('background-color', defaultColor);
        $this.css('background-color', defaultColor);
    });
});

检查小提琴

于 2013-08-01T19:25:03.207 回答
0

你可以用这个 javascript

     $('#inputDatabaseName').change(function () { 
         if($(this).val() ==="") {
             $(this).parents('#colorchange').css('backgroundColor','red');}
         else {
             $(this).parents('#colorchange').css('backgroundColor','green');
         }
     });
于 2013-08-01T19:36:12.560 回答