我有下面的 HTML 代码,还有一个用于输入关键字的文本框,
我想要的是当用户在此文本框中编写 javascript 使用 FirstName 和 LastName 在此 HTML 代码中搜索时,在比较项目时,如果项目不匹配我想 display: none
它的容器分区
我怎样才能使用 JS 做到这一点并在 firefox 和 IE 上工作
<div id="contact_4">
<input class="contactChk" id="chk_4" type="checkbox" />
<img alt="" src='img/4.jpg' width="25px" height="25px" />
<span id="contactName_4" class="contactItem">
FirstName LastName
</span>
<br />
</div>
<div id="contact_5">
<input class="contactChk" id="chk_5" type="checkbox" />
<img alt="" src='img/5.jpg' width="25px" height="25px" />
<span id="contactName_5" class="contactItem">
ACharName AnyLast
</span>
<br />
</div>
<div id="contact_6">
<input class="contactChk" id="chk_6" type="checkbox" />
<img alt="" src='img/6.jpg' width="25px" height="25px" />
<span id="contactName_6" class="contactItem">
BCharName AnyLast
</span>
<br />
</div>
<div id="contact_7">
<input class="contactChk" id="chk_7" type="checkbox" />
<img alt="" src='img/7.jpg' width="25px" height="25px" />
<span id="contactName_7" class="contactItem">
CCharName AnyLast
</span>
<br />
</div>
最佳答案
如果您要显示大量联系人,这看起来效率很低。最简单的方法是使用 jQuery并将函数绑定(bind)到文本字段的 keyup 事件:(假设上面的代码包含在类似 <div id="contactlist">
的内容中)
var searchstring = "";
function filterContact() {
var jthis = $(this); // should give a tiny performance gain
if ($('span.contactItem', this).text().toLowerCase().indexOf(searchstring) >= 0) {
jthis.addClass('matching');
jthis.removeClass('nonmatching');
} else {
jthis.addClass('nonmatching');
jthis.removeClass('matching');
}
}
function filterContacts() {
var elem = $('input#yourtextfield')[0];
searchstring = elem.value.toLowerCase(); // because we like to match all cases
searchstring = searchstring.replace(/^\s+/,'').replace(/\s+$/,''); // trim
$('#contactlist div').each(filterContact);
}
function initFiltering() {
$('input#yourtextfield').live('keyup',filterContacts);
}
$(document).ready(initFiltering);
同时添加 .matching
和 .nonmatching
类到你的 CSS。 (display: block
和 none
)
如前所述,这是非常低效的,不仅需要内存(和带宽),还需要 CPU 过滤时间(加上渲染时间)。如果您在某个数组中处理该数据,或者如果您有非常大的数据集,您应该根据需要从服务器获取分页的过滤数据(也可以通过 jQuery 的 AJAX 函数完成),它可能会更快。如果用户仍在打字,您还可以延迟过滤(仅当他停止打字约 500 毫秒时才过滤)。
toLowerCase()
非 ASCII 输入可能会有一些困难;所以如果你需要它,你应该在你的目标语言上测试它。
关于javascript - 在 html 中搜索 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/574816/