js / jq 常用整理

排序sort

sort() 方法用于对数组的元素进行排序。
语法: arrayObject.sort(sortby)
sortby 可选。规定排序顺序。必须是函数。

sort方法根据数组中对象的某一个属性值进行排序:

function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}

var arr = [
    {name:'Danny',age:10},
    {name:'Bob',age:18},
    {name:'Alice',age:8}
];
arr.sort(compare('age'));

最后结果是
{name:‘Alice’,age:8}
{name:‘Danny’,age:10}
{name:‘Bob’,age:18}

获取tr的索引

一般用$(this).index()
但如果两个tr之间穿插了script标签,获取其他的东西,会导致index获取不正确
可以用

/**
 * [get_tr_index 获取tr所在的索引]
 * @param  {[type]} obj [tr对象]
 * @return {[type]}     [description]
 */
function get_tr_index(obj){
	return $(this).index('tr');
}

该方法是获取当前tr在所有tr中的索引,包括其他table下的,仅获取当前table或者当前tbody下的tr可用下面的形式:

/**
 * [get_tr_index 获取tr所在的索引]
 * @param  {[type]} obj [tr对象]
 * @return {[type]}     [description]
 */
function get_tr_index(obj){
	return $(obj).parents('tbody').find('tr').index($(obj));
}

获取元素相对父元素的位置(偏移)-position()

该方法返回的对象包含两个整型属性:top 和 left,以像素计。

此方法只对可见元素有效。

$(selector).position()

获取元素相对文档的位置(偏移)-offset()

该方法返回或设置匹配元素相对于文档的偏移(位置)。

该方法返回的对象包含两个整型属性:top 和 left,以像素计。此方法只对可见元素有效。

$(selector).offset()

单选按钮的checked操作

  • 问题: 使用removeAttr(‘checked’)无效
    removeAttr(‘checked’)可以去掉jquery添加的checked,无法去掉点击加的
  • 解决: 换prop
$(':radio').prop('checked', false);
$(':radio').eq(0).prop('checked', true);

const、let、var区别

声明方式 变量提升 作用域 初始值 重复利用
const 块级 需要
let 块级 不需要
var 函数 不需要

监控input内容变化

$('#id').on('input propertychange',function(){ 

 })

获取英文字符串长度

String.prototype.getBytesLength = function() {
  var totalLength = 0;
  var charCode;
  for (var i = 0; i < this.length; i++) {
      charCode = this.charCodeAt(i);
      if (charCode < 0x007f)  {
          totalLength++;
      } else if ((0x0080 <= charCode) && (charCode <= 0x07ff))  {
          totalLength += 2;
      } else if ((0x0800 <= charCode) && (charCode <= 0xffff))  {
          totalLength += 2;
      } else{
          totalLength += 2;
      }
  }
  return totalLength;
}

截取指定长度的字符串(英文长度)

String.prototype.getBytesByLength = function(_len) {
  var totalLength = 0;
  var charCode;
  for (var i = 0; i < this.length; i++) {
      charCode = this.charCodeAt(i);
      if (charCode < 0x007f)  {
          totalLength++;
      } else if ((0x0080 <= charCode) && (charCode <= 0x07ff))  {
          totalLength += 2;
      } else if ((0x0800 <= charCode) && (charCode <= 0xffff))  {
          totalLength += 2;
      } else{
          totalLength += 2;
      }
      if (totalLength > _len) {
        return this.substring(0, i);
      } else if (totalLength == _len) {
        return this.substring(0, (i+1));
      }
  }
  return this.substring(0, _len);
}

猜你喜欢

转载自blog.csdn.net/weixin_42979149/article/details/84645865