跨行跨列
<table id="myTable" border='solid'>
<tr>
<th>姓名</th>
<th>课程</th>
<th>成绩</th>
</tr>
</table>
<script>
/**$(document).ready(function() {
var data = [
{ name: "张三", courses: [{ course: "数学", score: 90 }, { course: "语文", score: 85 }, { course: "英语", score: 88 }] },
{ name: "李四", courses: [{ course: "数学", score: 75 }, { course: "语文", score: 80 }] }
];
var $table = $("#myTable");
$.each(data, function(index, item) {
var rowspan = item.courses.length;
$.each(item.courses, function(courseIndex, courseItem) {
var $tr = $("<tr>");
if (courseIndex === 0) {
$tr.append($("<td>").attr("rowspan", rowspan).text(item.name));
}
$tr.append($("<td>").text(courseItem.course));
$tr.append($("<td>").text(courseItem.score));
$table.append($tr);
});
});
});**/
$(document).ready(function() {
var data = [
{
name: "张三",
nameRowspan: 3,
courses: [
{ course: "数学", scores: [{ score: 90 }] },
{ course: "语文", courseRowspan: 2, scores: [{ score: 88 }, { score: 88 }]}
]
},
{
name: "王五",
nameRowspan: 1,
courses: [
{ course: "数学", scores: [{ score: 90 }] },
//{ course: "语文", scores: [{ score: 0 }] }
]
},
{
name: "李四",
nameRowspan: 2,
courses: [
{ course: "数学", scores: [{ score: 75 }] },
{ course: "语文", scores: [{ score: 80 }] }
]
}
];
var $table = $("#myTable");
$.each(data, function(index, item) {
var rowspan = item.nameRowspan || 1;
var courseRowspan = 1;
$.each(item.courses, function(courseIndex, courseItem) {
if (courseItem.courseRowspan) {
courseRowspan = courseItem.courseRowspan;
}
$.each(courseItem.scores, function(scoreIndex, scoreItem) {
var $tr = $("<tr>");
if (courseIndex === 0 && scoreIndex === 0) {
$tr.append($("<td>").attr("rowspan", rowspan).text(item.name));
}
if (scoreIndex === 0) {
$tr.append($("<td>").attr("rowspan", courseRowspan).text(courseItem.course));
}
$tr.append($("<td>").text(scoreItem.score));
$table.append($tr);
});
});
});
});
</script>
隐藏
$("td").filter(function() {
return $.trim($(this).text()) === "";
}).hide();
css实现
td:empty {
display: none;
}
合并
$.merge()数组$.extend()对象
多个值判断成立
('pre'||'post')==='pre'//不可用错误的
if(('post'||'pre')||('pre'||'post')==='post')
循环
过滤
var arr = [1, 2, 3, 4, 5];
var newArr = $.grep(arr, function(value) {
return value % 2 === 0;
});
console.log(newArr); // 输出: [2, 4]
var t1=[[1,2,3],[4,5,6]]
t1.map(data=>data).join("||")//join返回数组
'1,2,3||4,5,6'
二维
var t1 = [[1, 2, 3], [4, 5, 6]];
var result = t1.map(function(row) {
return row.map(function(value) {
return value + 1;
});
});
console.log(result); // 输出:[[2, 3, 4], [5, 6, 7]]
var obj = {
name: 'John Doe',
age: 30,
occupation: 'Developer'
};
var newObj = {};
$.each(obj, function(key, value) {
newObj[key] = value + '66'; // 对每个属性值进行拼接
});
console.log(newObj);
// 输出: {name: "John Doe66", age: "3066", occupation: "Developer66"}
var arr = [1, 3, 1];
// 使用map方法遍历数组并将其中的1替换为3
var newArr = arr.map(function(item) {
if (item === 1) {
return 3;
} else {
return item;
}
});
console.log(newArr); // 输出: [3, 3, 3]
跳出循环
var arr = [1, 2, 3, 4, 5];
arr.some((item) => {
console.log(item);
if (item === 3) {
return true; // 跳出循环
}
return false;
});
转map
var jsonString = '{"key":1}';
var jsonObject = JSON.parse(jsonString);
var map = new Map(Object.entries(jsonObject));
console.log(map.get("key")); // 输出:1
区间
$(document).ready(function() {
var num = 5; // 要判断的数字
var min = 1; // 区间的最小值
var max = 10; // 区间的最大值
if (num >= min && num <= max) {
console.log("数字 " + num + " 在区间 [" + min + ", " + max + "] 内");
} else {
console.log("数字 " + num + " 不在区间 [" + min + ", " + max + "] 内");
}
});
// 输入字符串
var input_str = "106,108,121~130,156执行SB-A20-50";
// 提取数字和范围
var numbers_and_ranges = input_str.match(/\d+(?:~\d+)?/g);
// 将数字和范围转换为整数数组
var ranges_list = [];
for (var i = 0; i< numbers_and_ranges.length; i++) {
var item = numbers_and_ranges[i];
if (item.indexOf('~') !== -1) {
var start_end = item.split('~');
var start = parseInt(start_end[0], 10);
var end = parseInt(start_end[1], 10);
for (var j = start; j <= end; j++) {
ranges_list.push(j);
}
} else {
ranges_list.push(parseInt(item, 10));
}
}
// 判断122是否包含在范围内
var num_to_check = 0;
var is_included = ranges_list.includes(num_to_check);
console.log("122是否包含在范围内:", is_included);
全局定义
<script>
+function($){
$.llp=[
$.fn.extend({
test:function(){
alert(1)
},name:'34'
})
]
}($);
$(function(){
var test=$.llp;
console.log(test[0].test())
})
</scrip
拆分或者关系
var sbInfo1 = "SB-001-A前";
var sbInfo2 = "SB-001-A后";
// 使用正则表达式动态拆分前或后
var splitPattern = /(前|后)/;
// 拆分字符串
var splittedInfo1 = sbInfo1.split(splitPattern).filter(Boolean).map(item => item.trim());
var splittedInfo2 = sbInfo2.split(splitPattern).filter(Boolean).map(item => item.trim());
// 输出拆分结果
console.log("Splitted Info 1:", splittedInfo1);
console.log("Splitted Info 2:", splittedInfo2);
['SB-001-A', '前']0: "SB-001-A"1: "前"length: 2
['SB-001-A', '后']0: "SB-001-A"1: "后"length: 2
正则篇
var res = "SB-919-23-0006前;11~22执行SB-21-0012前且执行SB-22-123后";
// 使用正则表达式提取 SB 信息和前后标识
var sbPattern = /(SB-[A-Za-z0-9]+(-[A-Za-z0-9]+)*)(前|后)/gi
var sb=res.split(";")
var sbMatches = [];
$.each(sb,function(key,value){
// 批量提取所有匹配项
var sbMatch;
var mr = [];
while ((sbMatch = sbPattern.exec(value)) !== null) {
// 处理包含“且执行”关系的匹配项
if (value.includes('且执行')) {
mr.push({'sb':sbMatch[1], 'sta':sbMatch[3],'wz':sbMatch[0]})
} else {
var sbInfo = sbMatch[1];
var sbIds = sbInfo.split(/(前|后)/).filter(Boolean).map(item => item.trim());
// 将SB信息和匹配信息组合成期望的格式
var formattedMatch= {'sb':sbMatch[1], 'sta':sbMatch[3],'wz':sbMatch[0]}
sbMatches.push(formattedMatch);
}
}
if(mr.length>0)
sbMatches.push(mr);
})
console.log(JSON.stringify(sbMatches))
// 输出匹配到的信息
if (sbMatches.length > 0) {
sbMatches.forEach((item, index) => {
if (Array.isArray(item)) {
item.forEach((subItem, subIndex) => {
console.log(`Item ${index + 1}-${subIndex + 1}:`);
console.log(` sb: ${subItem.sb}`);
console.log(` sta: ${subItem.sta}`);
console.log(` wz: ${subItem.wz}`);
});
} else {
console.log(`Item ${index + 1}:`);
console.log(` sb: ${item.sb}`);
console.log(` sta: ${item.sta}`);
console.log(` wz: ${item.wz}`);
}
});
} else {
console.log("No match found");
}
截取两边重组
var str = "174执行SB-A21-20-01后或执行SB-A21-20-02后或执行SB-A21-20-01后";
// 正则表达式匹配"或执行"两侧的SB内容及状态
var sbRegex = /(SB-[A-Za-z0-9]+(-[A-Za-z0-9]+)*)(前|后)/gi;
// 正则表达式匹配"或执行"关键字
var orExecRegex = /或执行/g;
// 统计"或执行"的出现次数
var orExecCount = (str.match(orExecRegex) || []).length;
// 初始化数组用于存储SB信息
var sbArrays = [];
// 从头开始遍历SB信息
var sbArray = [];
var match;
var orExecIndex = 0;
while ((match = sbRegex.exec(str)) !== null) {
sbArray.push(match[1]);
// 当遇到“或执行”时,将当前SB信息数组添加到总数组中,并创建新的SB信息数组
if (orExecIndex < orExecCount && str.indexOf("或执行", match.index) === match.index + match[0].length) {
sbArrays.push(sbArray);
sbArray = [];
orExecIndex++;
}
}
// 处理最后一个SB信息数组
if (sbArray.length > 0) {
sbArrays.push(sbArray);
}
console.log(sbArrays.length); // 输出数组个数
console.log(sbArrays);
// 自定义CSS样式
<style>
p{color:green}
</style>
<p>这是一个段落。</p>
var style = document.createElement('style');
style.textContent = `
p{color:red}
`;
document.head.appendChild(style);
//document.body.appendChild(res);
隐藏
$(document).ready(function() {
$('li').each(function() {
$(this).children().eq(1).hide();
});
});
加入标签
$(document).ready(function() {
$('tps').replaceWith(function() {
return $('<span/>', {
class: 'red-text',
html: $(this).html()
});
});
});
// 在你的CSS文件中添加以下样式
.red-text {
color: red;
}
//围绕
$("#element").replaceWith(function() {
return "<div>" + $(this).text() + "</div>";
});
$("#element").replaceWith($("<div>新的jQuery对象</div>"));
var wrapper = $("<div class='wrapper'></div>");
$("#element").wrap(wrapper);
//指定节点标签加入样式
function wrapTextNodesWithSpan(element, color) {
$(element).not("button").contents().each(function() {
//var isParentButton = $(this).parent().is('button');
if (this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue)) {
// 检查当前节点是否直接位于设置了color样式的span内
var isParentSpan = $(this).parent().is('vb');
if (!isParentSpan) {//&&!isParentButton
var span = $("<vb style='color:" + color + "'>").text(this.nodeValue);
$(this).replaceWith(span);
}
} else if (this.nodeType === Node.ELEMENT_NODE && !$(this).is('vb')) { // 如果是元素节点且不包含设置了指定vb标签
// 将颜色样式传递给子元素,以便递归处理&&!$(this).is('button')
wrapTextNodesWithSpan($(this), color);
}
});
}
$(document).ready(function() {
//$('*:not(script):not(style)')
//wrapTextNodesWithSpan($('body').find("p"), 'red');//指定元素设置vb
//$(element).find('button').remove()
wrapTextNodesWithSpan($("body"),"red");//*
});
<label class="col-sm-2 control-label"><span style="color:red">性别:</span></label>
$(document).ready(function() {
// 选择页面中所有的元素及其文本节点
$('*').contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).each(function() {
// 如果文本节点不是空白字符,则包裹在<b>标签内
if (this.nodeValue.trim()) {
$(this).replaceWith($('<span style="color:red">').text(this.nodeValue));
}
});
});
var span = $("<b>").text(123);
$("p").contents().replaceWith(span);//<p><b>123</b></p>
$("#ab").parent().is("div") && $("#ab").parent().attr("id") == "vb")
<div id="vb"><p id="ab">2</p><div>
已有树,递归扁平化输出数据
const menuTree = [
{
id: 1,
name: '菜单1',
children: [
{
id: 2,
name: '子菜单1',
children: [
{
id: 3,
name: '子子菜单1',
},
{
id: 4,
name: '子子菜单2',
},
],
},
{
id: 5,
name: '子菜单2',
},
],
},
{
id: 6,
name: '菜单2',
children: [
{
id: 7,
name: '子菜单3',
},
],
},
];
function traverseMenuTree(menuTree) {
menuTree.forEach((menuItem) => {
console.log(menuItem.name);
if (menuItem.children) {
traverseMenuTree(menuItem.children);
}
});
}
traverseMenuTree(menuTree);
生成树数据
const treeData = [
{ id: 1, parentId: null, name: '节点1' },
{ id: 2, parentId: 1, name: '节点1-1' },
{ id: 3, parentId: 1, name: '节点1-2' },
{ id: 4, parentId: 2, name: '节点1-1-1' },
{ id: 5, parentId: 2, name: '节点1-1-2' },
{ id: 6, parentId: 3, name: '节点1-2-1' },
{ id: 7, parentId: null, name: '节点2' },
{ id: 8, parentId: 7, name: '节点2-1' },
];
function generateTree(treeData, parentId = null) {
const tree = [];
treeData.forEach((item) => {
if (item.parentId === parentId) {
const children = generateTree(treeData, item.id);
if (children.length > 0) {
item.children = children;
}
tree.push(item);
}
});
return tree;
}
const tree = generateTree(treeData);
console.log(tree);
根据id找出所有父节点数据
const menuTree = [
{
id: 1,
name: '菜单1',
children: [
{
id: 2,
name: '子菜单1',
children: [
{
id: 3,
name: '子子菜单1',
},
{
id: 4,
name: '子子菜单2',
},
],
},
{
id: 5,
name: '子菜单2',
},
],
},
{
id: 6,
name: '菜单2',
children: [
{
id: 7,
name: '子菜单3',
},
],
},
];
function findParentNodesById(menuTree, targetId, parents = []) {
let found = false;
for (const menuItem of menuTree) {
if (menuItem.id === targetId) {
found = true;
break;
}
if (menuItem.children) {
const result = findParentNodesById(menuItem.children, targetId, [...parents, menuItem]);
if (result.found) {
return result;
}
}
}
return { found, parents };
}
const result = findParentNodesById(menuTree, 4);
if (result.found) {
console.log('找到了 ID 为 4 的节点,其父节点为:');
result.parents.forEach((parent) => console.log(parent.name));
} else {
console.log('未找到 ID 为 4 的节点');
}
JSON字符串""替换为’单引号
"{"key1": "value1", "key2": "value2"}".replace(/^"/, '\'').replace(/"$/, '\'');
隐藏
<table>
<tr data-range="S1">
<td>11</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr data-range="S2">
<td>22</td>
</tr>
</table>
<script>
// 获取具有 data-range 属性的所有 tr 元素
const trsWithDataRange = document.querySelectorAll("tr[data-range]");
// 遍历 tr 元素并隐藏相邻的第一个 tr 元素
//trsWithDataRange.forEach((tr) => {
// const nextTr = tr.nextElementSibling;
// if (nextTr) {
// nextTr.style.display = "none";
// }
//});
// 遍历 tr 元素并隐藏相邻的多个 tr 元素
trsWithDataRange.forEach((tr) => {
let nextTr = tr.nextElementSibling;
while (nextTr && !nextTr.hasAttribute("data-range")) {
nextTr.style.display = "none";
nextTr = nextTr.nextElementSibling;
}
});
</script>
条件判断
if (targetElement.nextElementSibling.classList.contains('related')) {
console.log('Next element has the "related" class.');
}
增加元素
<table width=500 >
<tr data-range="S1">
<td>11</td>
</tr>
<tr>
<td id='reference'>2</td>
</tr>
</table>
let newElement = document.createElement('div');
newElement.textContent = 'New Element';
let referenceElement = document.querySelector('#reference');
let insertionPoint = referenceElement.nextElementSibling;
if (insertionPoint) {
referenceElement.parentNode.insertBefore(newElement, insertionPoint);
} else {
referenceElement.parentNode.appendChild(newElement);
}
// 将新增的 div 元素插入到 td 元素的子节点中<td id="reference">2<div>New Element</div></td>
//注释则是新增元素放到td后<tr><td id="reference">2</td><div>New Element</div></tr>
//referenceElement.appendChild(newElement);
//创建一个新元素并设置其内容,然后找到reference元素的下一个同级元素(insertionPoint)。如果有,就在两者之间插入新元素;否则,将新元素添加到reference元素的父节点末尾。
增加事件
<table width="500">
<tr>
<td>t1</td>
<td>t2</td>
<td>t3</td>
<td>t4</td>
</tr>
<tr data-range="S1">
<td>001</td>
<td class="cli">002</td>
<td>003</td>
<td>004</td>
</tr>
</table>
let container = document.querySelectorAll('tr[data-range="S1"] .cli');
container.forEach(function(element) {
element.addEventListener('click', function() {
console.log('Clicked element with class "cli" in a row with data-range="S1"');
});
});