搜索div

时间:2015-04-28 19:38:28

标签: javascript search indexof

我发现了这篇帖子How to perform a real time search and filter on a HTML table,我想让它适应搜索div。

Html:

<input type="text" id="search" placeholder="Type to search">  
<table id="table">
    <tr>
        <div class="panel panel-default">
            <!-- Default panel contents -->
            <div class="panel-heading">Panel 1</div>
            <div class="panel-body">
                <p>1</p>
            </div>
        </div>
    </tr>
    <tr>
        <div class="panel panel-default">
            <!-- Default panel contents -->
            <div class="panel-heading">Panel 2</div>
            <div class="panel-body">
                <p>2</p>
            </div>
        </div>
    </tr>
</table>

JS:

var $rows = $('#table tr');
$('#search').keyup(function() {
  var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
    reg = RegExp(val, 'i'),
    text;

  $rows
    .show()
    .filter(function() {
      text = $(this).text().replace(/\s+/g, ' ');
      return !reg.test(text);
    })
    .hide();
});

有人可以解释如何在我的div中访问内容(在这里,在&#34; panel-heading&#34;)?

1 个答案:

答案 0 :(得分:0)

您的HTML无效。 tr元素只能包含tdth个子元素。您应该使用tr元素包装td内容。

这是我的Chromium浏览器渲染您的html的方式:

<input type="text" id="search" placeholder="Type to search">
<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel 1</div>
    <div class="panel-body">
        <p>1</p>
    </div>
</div>
<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel 2</div>
    <div class="panel-body">
        <p>2</p>
    </div>
</div>
<table id="table">
    <tbody>
        <tr></tr>
        <tr></tr>
    </tbody>
</table>

修复标记,JavaScript代码段将有效。