JavaScript常用操作方法

1.字符串反转

var str = "abcdefghijklmn";
str = str.split('').reverse().join("");

2.字符串部分截取(从下标为1的字符截取到最后一个)

var str = "abcdefghijklmn";
str = str.split('').slice(1, res.length).join("");

3.判断数据类型是否为undefined

var str;
if(typeof(str) == "undefined") console.log("str is undefined");

4.四舍五入函数

console.log(Math.round(1.53))//输出2
console.log(Math.round(1.13))//输出1
console.log(Math.round(1.92))//输出2
console.log(Math.round(1.50))//输出2
console.log(Math.round(1.49))//输出1

5.获取点击对象DOM的id

$(this).attr("id")

6.获取点击对象DOM在该层级的索引下标

$(this).index()

7.隐藏除自身外的其他同级元素

// 隐藏其他subContainer
$('.sub_container:eq(' + $(this).index() + ')').siblings().filter('.sub_container').css({'display': 'none'});

8.默认点击第一个

// 默认点击第一个
$('.sub_container:eq(' + $(this).index() + ') .sub_tab_item:eq(0)').click();

9.map的使用

10.判断有几个相同元素

<tbody>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
</tbody>
$("tbody tr").length

11.判断是否存在对应元素

$('#no_use_data').length && $('#no_use_data').length > 0

12.在指定DOM元素前面/后面增加元素

let yx_sub_class_tab_html = '<div>Hello World</div>';
// 前
$(".tab-content").parent().before(yx_sub_class_tab_html);
// 后
$(".tab-content").parent().after(yx_sub_class_tab_html);

猜你喜欢

转载自blog.csdn.net/weixin_43823060/article/details/131416366