JavaScript 组件编写

说明

这是一个联系人名过滤组件,还提供可选的“大小写是否敏感”选项,默认大小写不敏感

一、HTML 结构

<ul class="contacts">
    <li class="h-card">
        <a href="http://jakearchibald.com" class="p-name u-url">Jake Archibald</a>
        (<a href="mailto:jake@example.com" class="u-email">e-mail</a>)
   </li>
   <li class="h-card">
        <a href="http://christianheilmann.com" class="p-name u-url">Christian Heilmann</a>
        (<a href="mailto:christian@example.com" class="u-email">e-mail</a>)
   </li>
   <li class="h-card">
        <a href="http://ejohn.org" class="p-name u-url">John Resig</a>
        (<a href="mailto:john@example.com" class="u-email">e-mail</a>)
   </li>
   <li class="h-card">
        <a href="http://www.nczonline.net" class="p-name u-url">Nicholas Zakas</a>
        (<a href="mailto:nicholas@example.com" class="u-email">e-mail</a>)
   </li>
</ul>

二、组件代码(依赖 jQuery)

<script type="text/javascript" src="../js/vendor/jquery-3.1.1.min.js"></script>

<script type="text/javascript">
function startsWith(str, value, caseSensitive) {
     if(!caseSensitive) {
         str = str.toLowerCase();
         value = value.toLowerCase();
     }
     return str.indexOf(value) === 0;
 }

// FilterWidget.js
function FilterWidget(contactList) {
    var self = this;
    this.contacts = contactList;
    this.filterField = $('<input type="search" />').insertBefore(contactList);
    this.tipWords = $('<label>大小写敏感?</label>').insertBefore(contactList);
    this.caseSwitch = $('<input type="checkbox" />').insertBefore(contactList);
    this.caseSensitive = this.caseSwitch.prop("checked");
    this.filterField.on("keyup", function(ev) {
        var handler = self.onFilter;
        return handler.call(self, ev);
    });
    this.caseSwitch.on("change", function(ev) {
        var handler = self.onToggle;
        return handler.call(self, ev);
    });
 }

FilterWidget.prototype.onFilter = function(ev) {
     var names = this.contacts.find("li .p-name");
     var input = ev.target.value.trim();
     var self = this;
     names.each(function(i, node) {
         var el = $(node);
         var name = el.text();
         var contact = el.closest(".h-card");

         var match = startsWith(name, input, self.caseSensitive);

         if(match) {
             contact.show();
         } else {
             contact.hide();
         }
    });
}

FilterWidget.prototype.onToggle = function(ev) {
     this.caseSensitive = this.caseSwitch.prop("checked");
     this.filterField.trigger("keyup");
};
</script>

三、使用组件

new FilterWidget($('ul.contacts'));

(完)

posted @ 2017-03-29 15:38  Hi!张宝  阅读(261)  评论(0编辑  收藏  举报