Home  >  Article  >  Web Front-end  >  jQuery implements the method of getting bound custom event elements_jquery

jQuery implements the method of getting bound custom event elements_jquery

WBOY
WBOYOriginal
2016-05-16 15:28:061509browse

The example in this article describes the jQuery method of obtaining and binding custom event elements. Share it with everyone for your reference, the details are as follows:

(function ($) { // 自定义itemtab事件
$.fn.bind = function(types, data, fn) { // 重载jQuery.fn.bind方法,用来截获绑定自定义事件的元素
 if(typeof types == 'string' && 'itemtab' == types) {
 var itemTouchStart = -1; // touchstart位置
 var itemTouchMove = -1; // touchend位置,值为-1时表示未触发
 var itemTriggerDistance = 0; // 拖动距离阀值,若大于该值则为拖动列表,若小于等于该值则为点击列表项
 var itemMoved = false; // 列表是否为拖动状态
 $(this).bind('touchstart', function (event) {
  if(!event.originalEvent.touches.length) return true;
  itemMoved = false;
  itemTouchStart = event.originalEvent.touches[0].pageX; // 记录起始位置
 }).bind('touchmove', function (event) {
  if(!event.originalEvent.touches.length) return true;
  itemTouchMove = event.originalEvent.touches[0].pageX; // 当前拖动位置
  //console.log('touchmove:', itemTouchStart, itemTouchMove, itemMoved);
  if(Math.abs(itemTouchMove - itemTouchStart) > itemTriggerDistance) {
  itemMoved = true; // 列表被拖动
  }
 }).bind('touchend', function (event) {
  //console.log('itemMoved:', itemMoved);
  if(itemMoved) { // 列表被拖动过,非点击操作
  return true;
  }
  $(this).trigger('itemtab'); // 触发自定义事件
 });
 }
 return this.on( types, null, data, fn ); // 这种做法具有侵入性,多个类似的代码会相互覆盖,可采用深度复制方式调用原$.fn.bind方法
}
})(jQuery);

I hope this article will be helpful to everyone in jQuery programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn