winney

It is never too old to learn.

0%
winney

appendTo()

将动态生成的元素添加到指定的目标元素中作为子元素

html

1
<div class="target-element"></div>

jQuery

1
$('<div class="dynamic-element">...</div>').appendTo('.target-element');
1
2
3
4
5
6
7
8
9
10
11
var html = 
`
<ul>
<li>新闻11111</li>
<li>新闻22222</li>
<li>新闻33333</li>
<li>新闻44444</li>
</ul>
`;

$(html).appendTo('.target-element');

append()

将动态生成的元素添加到指定的父元素中

html

1
<div class="parent-element"></div>

jQuery

1
$('.parent-element').append('<div class="dynamic-element">...</div>');
1
2
3
4
5
6
7
8
9
10
11
var html = 
`
<ul>
<li>新闻11111</li>
<li>新闻22222</li>
<li>新闻33333</li>
<li>新闻44444</li>
</ul>
`;

$('.parent-element').append(html);

on()

使用事件委托机制绑定事件处理程序,可以捕获动态生成元素的事件

使用 .on() 方法绑定事件时,应该选择一个静态的父元素,并通过选择器指定目标动态生成的元素。这样可以确保事件处理程序能够捕获到动态生成元素的事件。

对动态生成的元素进行操作,应该确保在元素已经生成并添加到 DOM 树中后再执行相应的操作,以避免操作无效。

1
$(document).on('click', '动态生成的元素的选择器', function() { ... });
1
$(父元素的选择器).on('click', '动态生成的元素的选择器', function() { ... });

html

1
<div class="news-box"></div>

jQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var html = 
`
<ul>
<li>新闻11111</li>
<li>新闻22222</li>
<li>新闻33333</li>
<li>新闻44444</li>
</ul>
`;

$('.news-box').append(html);

$('.news-box').on('click', 'ul li', function(e){
console.log('点击某条新闻')
console.log(this); // <li>新闻11111</li>
console.log(e.target); // <li>新闻11111</li>
console.log($(this).index()) // 0
});

live() 方法在旧版本的 jQuery 中用于绑定事件处理程序,包括对动态生成的元素的事件进行绑定。然而,自 jQuery 版本 1.7 起,live() 方法已被废弃,不再推荐使用。

remove()

从 DOM 中移除动态生成的元素

1
$('.dynamic-element').remove();

empty()

清空动态生成元素的内容

1
$('.dynamic-element').empty();

获取URL中的参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
** @param name{string} // 参数名
*/
function getURLParam(name) {
// 获取完整的查询参数字符串
const queryString = window.location.search;

// 创建URLSearchParams对象来解析查询参数
const params = new URLSearchParams(queryString);

// 使用get方法获取指定名称的参数值
return params.get(name);
}

http://127.0.0.1:5500/URL.html?username=test&age=18

1
2
3
4
5
const username = getURLParam('username');
console.log(username); // "test"

const age = getURLParam('age');
console.log(age); // "18"

解析URL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const urlString = 'https://www.test.com:8080/path/url.html?username=test&age=18';
const url = new URL(urlString);

console.log(url.protocol); // "https:"
console.log(url.host); // "www.test.com:8080"
console.log(url.pathname); // "/path/url.html"
console.log(url.search); // "?username=test&age=18"
console.log(url.hostname); // www.test.com
console.log(url.href); // https://www.test.com:8080/path/url.html?username=test&age=18
console.log(url.origin); // https://www.test.com:8080
console.log(url.port); // 8080

// 解析查询参数
const searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('username')); // "test"
console.log(searchParams.get('age')); // "18"

构建URL

在页面之间传参,不想手动把参数使用&符号一个一个拼起来时

  1. 使用URL构造函数构建URL

    1
    2
    3
    4
    5
    const url = new URL('https://www.test.com');
    url.pathname = '/path';
    url.searchParams.set('username', 'test');
    url.searchParams.set('age', '18');
    console.log(url.toString()); // "https://www.test.com/path?username=test&age=18"
  2. 使用字符串拼接构建URL

    1
    2
    3
    4
    5
    const baseUrl = 'https://www.test.com';
    const path = '/path';
    const params = new URLSearchParams({ username: 'test', age: '18' });
    const constructedUrl = `${baseUrl}${path}?${params.toString()}`;
    console.log(constructedUrl); // "https://www.test.com/path?username=test&age=18"

参数对应的值带=

如果动态传参时,参数对应的值含有=号,避免浏览器自动处理等号,使用encodeURIComponent方法

发送端:

1
2
3
4
const key = "BANXB1cAPFcEAGwFZgk=";
const encodedValue = encodeURIComponent(key);
const url = `edit.html?key=${encodedValue}`;
window.location.href = url;

接收端:

1
2
3
4
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const encodedValue = urlParams.get("key");
const decodedValue = decodeURIComponent(encodedValue);

因在项目中使用$.form.href("{:url('xy/test/group')}" + "?id=" + id + '&key='+key);这样跳转到页面2。其中key的值最后可能带有=号,跳转到页面2的时候,在页面2中获取到的key参数少了最后的=

如果大家使用window.location.href进行页面跳转时,在链接上传参,没有问题,可以忽略这个问题。

将网址url中的参数转化为JSON格式的两种方法

第一种: for 循环方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 第一种: for循环
var GetQueryJson1 = function () {
let url = location.href; // 获取当前浏览器的URL
let arr = []; // 存储参数的数组
let res = {}; // 存储最终JSON结果对象
arr = url.split('?')[1].split('&'); // 获取浏览器地址栏中的参数

for (let i = 0; i < arr.length; i++) { // 遍历参数
if (arr[i].indexOf('=') != -1){ // 如果参数中有值
let str = arr[i].split('=');
res[str[0]] = str[1];
} else { // 如果参数中无值
res[arr[i]] = '';
}
}
return res;
}
console.log(GetQueryJson1());

第二种:正则表达式方式

1
2
3
4
5
6
7
8
9
10
11
12
// 第二种:正则表达式
var GetQueryJson2 = function () {
let url = location.href; // 获取当前浏览器的URL
let param = {}; // 存储最终JSON结果对象
url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) {
param[v] = decodeURIComponent(k);//解析字符为中文
return k + '=' + v;
});
return param;
}

console.log(GetQueryJson2());

URL参数改为json格式

1
2
3
4
5
6
7
var data = $(formEl).serialize()                // 表单数据(筛选条件)
,arr = decodeURIComponent(data).split("&") // 对数据拆分处理
,formData = {} // 需要缓存的数据对象
// 转为JSON对象
arr.map(function(item) {
formData[item.split('=')[0]] = item.split('=')[1];
})

修改url参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function changeURLArg(url,arg,arg_val){ 
var pattern=arg+'=([^&]*)';
var replaceText=arg+'='+arg_val;
if(url.match(pattern)){
var tmp='/('+ arg+'=)([^&]*)/gi';
tmp=url.replace(eval(tmp),replaceText);
return tmp;
}else{
if(url.match('[\?]')){
return url+'&'+replaceText;
}else{
return url+'?'+replaceText;
}
}
return url+'\n'+arg+'\n'+arg_val;
}

改变hash值

1
2
3
4
//改变hash值
function changeHash(key, val) {
location.hash= location.hash.match(key+"=([^&]*)") ? location.hash.replace(eval('/('+ key+'=)([^&]*)/gi'), key+"="+val) : location.hash + "&"+key+"="+val
}

判断一个对象数组的某个对象是否具体某个属性,如果没有就追加对象

1
2
3
4
// records是对象数组
if (!records.some(obj => obj.username === value.username)) {
records.push(value);
}

js高效修改对象数组里的对象属性名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
appList: [
{
list:[
{id: 118, name: "测试1", group_id: 4, os: 2}
{id: 120, name: "测试11", group_id: 4, os: 2}
{id: 123, name: "测试111", group_id: 4, os: 1}
]
name: "测试1111"
},
{
list:[
{id: 118, name: "测试2", group_id: 4, os: 2}
{id: 120, name: "测试22", group_id: 4, os: 2}
{id: 123, name: "测试222", group_id: 4, os: 1}
]
name: "测试2222"
},
]

(因为插件的要求)改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
productArr: [
{
children:[
{value: 118, name: "测试1", group_value: 4, os: 2}
{value: 120, name: "测试11", group_value: 4, os: 2}
{value: 123, name: "测试111", group_value: 4, os: 1}
]
name: "测试1111"
},
{
children:[
{value: 118, name: "测试2", group_value: 4, os: 2}
{value: 120, name: "测试22", group_value: 4, os: 2}
{value: 123, name: "测试222", group_value: 4, os: 1}
]
name: "测试2222"
},
]

代码:

1
2
var productArr = JSON.parse(JSON.stringify(appList).replace(/list/g, 'children'));
productArr = JSON.parse(JSON.stringify(productArr).replace(/id/g, 'value'));
【参考】: js高效修改对象数组里的对象属性名