使用Javascript中的复选框搜索文本框

Search textbox using checkbox in Javascript

本文关键字:搜索 文本 复选框 Javascript 使用      更新时间:2023-09-26

我正在尝试使用复选框进行文本搜索。例如,如果用户选中复选框,它将显示用户在搜索框中输入的单词/字母(该单词/字母将突出显示)。假设我输入"the",它将在段落中搜索所有的"the"并突出显示所有的"the"。我已经记下了第一部分,我不明白的是如何使复选框与文本搜索表单相连接。因此,当用户选择复选框时,将显示"或他们在搜索框中输入的任何单词/字母。

我想用if语句。。。

因此,如果您想与该复选框交互,可以执行以下操作:

$(':checkbox').on('change', function() { 
    if ($(this).is(':checked')) { 
        // do your search thing 
    } else {
        // turn off your search thingy
    } 
});

Fiddle

您可以使用这样的东西:

$(':checkbox').on('change', function() {
    if ($(this).is(':checked')) {
        $(".content").addClass("highlight");
    } else {
        $(".content").removeClass("highlight");
    }
});

在CSS中,你需要有:

.highlight {background: #99f;}

代码段

$(function () {
  text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt repellat sint eligendi adipisci consequuntur perspiciatis voluptate sunt id, unde aspernatur dolor impedit iure quaerat possimus nihil laboriosam, neque, accusamus ad.";
  $(".content").text(text);
  $(':checkbox').on('change', function() {
    if ($(this).is(':checked')) {
      $(".content").addClass("highlight");
      $(".content").html(text.replace(/lo/gi, '<span>lo</span>'));
    } else {
      $(".content").removeClass("highlight");
    }
  });
});
.check + input {display: none;}
.check:checked + input {display: inline-block;}
.highlight span {background: #ccf;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" class="check" />
<input type="text" placeholder="Type your terms..." class="term" />
<div class="content"></div>

也许是类似上面的东西。