【问题标题】:Using JavaScript / jQuery to Search Keywords使用 JavaScript / jQuery 搜索关键字
【发布时间】:2012-10-06 21:27:41
【问题描述】:

我有一个静态网站,我想知道是否可以在网站上有一个搜索表单,然后使用 jQuery 的 JavaScript 在页面上搜索某些关键字,然后使用 jQuery 添加一个类或其他东西。

【问题讨论】:

标签: javascript jquery search


【解决方案1】:

使用 JQuery“包含”选择器

然后使用 addClass() 方法来分配你的类

  • http://api.jquery.com/addClass/

    <html>
    <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
    
    <div>John Resig</div>
    
    <div>George Martin</div>
    <div>Malcom John Sinclair</div>
    <div>J. Ohn</div>
    
    
    <script>
    $("div:contains('John')").css("text-decoration", "underline");
        </script>
    
    </body>
    </html>
    

【讨论】:

  • jQuery.contains 不进行文本匹配,它在其他元素中查找元素(例如 &lt;A&gt;&lt;DIV&gt; 中。
  • 没关系,我想的是contains() 函数,而不是:contains 选择器。
【解决方案2】:

应该可以:

var text = $('body').html();
var split = text.split(/whatever/);
$('body').html(split[0] + '<span class="match">' + 'whatever' + '</span> + split[1]); 

【讨论】:

  • 如果搜索字符串匹配 HTML 中的某些内容而不是呈现的文本,这将破坏事情。
  • -1 这也将替换元素属性并可能破坏页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多