javascript - 从输入中获取变量并使用它来更改 css 类

标签 javascript jquery html css

我有一个输入框 id="search" .

<input id="search" type="text" />

也有几个<div>包含一些文本,如下所示:

<div id="textblock">Some text here</div>
<div id="textblock">Some other text here</div>
<div id="textblock">Few strokes</div>
<div id="textblock">More words</div>

我需要更改 <div> 的样式( display:none ) 如果 <div>有用户在旅途中在输入字段中键入的文本。

例如,如果输入中的值为“strokes”,则带有单词“strokes”的 div(或 div)会消失:

<div id="textblock">Some text here</div>
<div id="textblock">Some other text here</div>
<div id="textblock">More words</div>

我一直在寻找一个 jQuery 解决方案,我找到了一些代码,但我无法将它们组合成一个工作片段。我知道我应该使用 keyUp()功能,:contains()等等

最佳答案

首先,id 属性必须唯一 - 您不能有多个具有相同 ID 的元素。相反,您应该使用 class 属性:

<div class="textblock">Some text here</div>
<div class="textblock">Some other text here</div>
<div class="textblock">Few strokes</div>
<div class="textblock">More words</div>

要进行过滤,您可以使用 jQuery's :contains() selector确定哪些 .textblock 元素包含输入到 input 元素中的文本。为此,我使用了 blur event handler这将在 input 元素不再具有焦点时触发:

$('#search').on('blur', function() {
    $('.textblock:contains(' + this.value + ')').hide();
});

JSFiddle demo .

如果您希望在内容输入到 input 元素时立即发生这种情况,我们可以使用 input 事件处理程序来代替并结合 :contains( )jQuery's :not() selector显示以前可能被隐藏的元素:

$('#search').on('input', function() {
    $('.textblock:contains(' + this.value + ')').hide();
    $('.textblock:not(:contains(' + this.value + '))').show();
});

JSFiddle demo .

正如 Dreamonic 在 comments 中指出的那样在这里,如果您随后想要处理用户从 input 元素中删除内容,我们需要确保我们不会将空输入与 .textblock 内容相匹配.我们可以使用 trim() 来做到这一点:

$('#search').on('input', function() {
    if (this.value.trim().length > 0) {
        $('.textblock:contains(' + this.value + ')').hide();
        $('.textblock:not(:contains(' + this.value + '))').show();
    }
    else
        $('.textblock').show();
});

JSFiddle demo .

Example

关于javascript - 从输入中获取变量并使用它来更改 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25198709/

相关文章:

javascript - 如何在 Angular JS 中创建服务?

javascript - 获得真实类型原型(prototype)与构造函数?

javascript - 使用格式化程序的 JqGrid 内联编辑

javascript - 如何使用 jQuery 显示/隐藏隐藏的(默认情况下)表格行?

javascript - 防止从周围激活菜单

javascript - 从其他页面提取数据

javascript - npm install @material-ui/core 出现错误 : Unexpected end of JSON input while parsing

javascript - 通过 HTML 文档与 Electron 交互

jQuery .blur 不起作用

javascript - 如何在PHP中获取用户的电脑IP