jQuery+js实际应用开发知识总结

司徒兴思
2023-12-01

(一)jquery循环遍历

$('input[type=checkbox][name=check_subjectid]:checked').each(function(i,o){
             if(o.getAttribute("seriestype") == 3)
                  {
             $.umapMessager.alert('<bean:message key="IPTV.SLCS.TITLE"/>', '<bean:message 			  key="contentmgr.content.series.dele_error1"/>', 'error' , function(r){});
      retflag = true;
}
});

单选框取值和动态复制网址:添加链接描述

js及HTML5的基础学习 添加链接描述

css样式 添加链接描述

(二)表单序列化

/**
 * 获得form表单元素
 * @param formObj
 * @returns
 */
function changeAjaxFormData(formObj){
var data=formObj.serialize();
data= decodeURIComponent(data,true);// 防止中文乱码
var json=formToJson(data);// 转化为json
return JSON.parse(json);
}
function formToJson(data) {
   data=data.replace(/&/g,"\",\"").replace(/=/g,"\":\"").replace(/\+/g," ").replace(/[\r\n]/g,"<br>");
   data="{\""+data+"\"}";
   return data;
}
var formJson = changeAjaxFormData($("#actionForm"));
ajaxTemplate("/admin/product/addProduct","json", true, formJson, function(data){
    
/*
*例如*/:
function addemand_require_info2(){
	var JSONObj=new Object();//为JSON对象  
	var requireWorkloadList=[];//生成集合(保存多个商品对象)
	//var GoodsSize=$('#GoodsSize').val();//获取商品对象的数量
	var requireWorkload=null;//保存商品对象  
	//循环将多个商品对象保存到集合中
	for (var i = 1; i<13; i++) {  
		requireWorkload=new Object();//生成一个商品对象
		requireWorkload.requireid = $("#requireid").val();
		requireWorkload.moduleworkload=$('#gzl'+i).val();
		requireWorkload.modulename=$('#gzl'+i).attr("name");//保存商品名称
		requireWorkloadList.push(requireWorkload);//保存商品对象到集合中  
	}
	JSONObj.jsonStr=JSON.stringify(requireWorkloadList);//将集合转成JSON("jsonStr"用于后台定位)
	
	/*var data = $("#add_Demand_form").serialize();
	data = decodeURIComponent(data,true);//防止中文乱码
	data = data.replace(/&/g,"\",\"");
    data = data.replace(/=/g,"\":\"");
    data = "{\""+data+"\"}";
    data = JSON.parse(data);
    JSONObj.data = JSON.stringify(data);*/
    
    //alert("111:"+JSONObj.jsonStr+"222:"+JSONObj.data);
    
	$.ajax({
		type:'post',
		async: false,
	    data : JSONObj,
	    url: '/saltportal/demand/addDemandList',
	    dataType:"json",
        success: function(data){
        	alert("提示:"+data.result);
        	//feedback(relid);
        	window.location.href="";
         },error:function(err){
        	 alert("提示error:"+err.result);
         }
	})
}

(三)常用jQuery代码支持工作

(1)隐藏显现

	$("#aid2").show(); //显现
	$("#aid1").hide(); //隐藏

(2)设置默认值

$("#servicenameA").attr("value",data.servicename); //设置value值
$("#jiben_smname").val(data[0].smname); //给select设置默认值 data是ajax返回值

(3)直接请求路径

	function _go(pageNum){
	var servicename = $("#servicename").val();
	var pageNum = pageNum;
	location='/saltportal/serviceInfo?servicename='+servicename+'&pageNum='+pageNum;	
}

(4)返回主页面并刷新

window.location.href="";
//history.go(-1) :后退+刷新;
//history.go(1) :前进
//history.back() :后退 ; 
//history.back(-1) :返回上一页,原页表表单中的内容会保留
//history.back(0) :刷新;
//history.back(1) : 前进 

(5)跳转路径

th:href="@{${model中的name值}}"
th:href="@{/demand(username=${username})}"
js:  href="'+obj.icenterurl+'"

(6)弹出新窗口

function icenterpage(icenterurl){
	window.open(icenterurl,'','height=600,width=1000,top=140,left=300');
}

(7)ajax异步请求填补html数据

function serciceList(requireid){
	$.ajax({
		type: 'GET',
		async: false,
	   	url: '/saltportal/demand/getSerciceList?requireid='+requireid,
	    	dataType: "json",
		//data: {requireid : requireid},
        	success: function(data){
        	$("#sercice_requireid").attr("value",requireid);
        	$('#sercice_list').empty();
        	html="";
        	html+='<table class="table table-striped"><thead><tr><th>归属服务编号</th><th>归属服务名称</			th><th>服务编号</th><th>服务名称</th><th>icenterurl</th><th>操作</th></tr></thead>';
        	for (var i=0;i<data.length;i++ ){
        		html+='<tr id="rowOne">';
        		html+='<td>'+data[i].parentcode+'</td>';
        		html+='<td>'+data[i].parentname+'</td>';
        		html+='<td>'+data[i].servicecode+'</td>';
        		html+='<td>'+data[i].servicename+'</td>';
        		html+='<td><a style="width:200px; cursor:pointer;" onclick="icenterpage(\''+data				[i].icenterurl+'\');">'+data[i].icenterurl+'</a></td>';
        		html+='<td><button  data-target="#step1" onclick="delSerciceByid(\''+requireid+'\',			\''+data[i].servicecode+'\');"><a>删除</a></button><br>';
        		html+='</tr>';
        	}
        	html+='</tbody>';
        	html+='</table>';
        	html+='<div class="modal-footer">';
    		html+='<button type="button"  class="btn btn-primary" onclick="queSercice				(\''+requireid+'\')">增加</button></div>';
    		$("#sercice_list").append(html);
         	},error:function(err){
        	 	alert("服务树初始化数据加载失败!");
         	}
		});
}

(8)选项框条件补充

//页面初始化赋值
function loadRolename3Options(Rolename3){
	var newRolename3=Rolename3.substring(1,Rolename3.length-1);
	var arr=newRolename3.split(",");
	$("#qaname").append('<option value="">--请选择--</option>');
	for(var i=0;i<arr.length;i++){
		$("#qaname").append('<option value="'+trim(arr[i])+'">'+arr[i]+'</option>');
		$("#jiben_qaname").append('<option value="'+trim(arr[i])+'">'+arr[i]+'</option>');
	}
}

//去除字符串前后空格
function trim(str){ 
	return str.replace(/(^\s*)|(\s*$)/g, ""); 
}

(四)html部分代码

把div变成input输入框<div></div>

contenteditable="plaintext-only"
或者contenteditable="true"

*<span></span>标签也可以用

跳出新窗口,用于href=""访问
<1>iframe  缺点:https或者http请求的连接地址一些会受返回的信息不同而不通过
<iframe id="icenterurlPage" name="icenterurlPage" style="width:100%; height:500px; overflow:auto;" 	frameborder="0" src="" marginheight="0" marginwidth="0"></iframe>
<2>window.open();   //推荐使用

window.open ('page.html', 'newwindow', 'height=100, width=400, top=0, left=0, toolbar=no, menubar=no, 	scrollbars=no, resizable=no,location=n o, status=no')

 <SCRIPT LANGUAGE="javascript"> js脚本开始; 
  window.open 弹出新窗口的命令; 
  'page.html' 弹出窗口的文件名; 
  'newwindow' 弹出窗口的名字(不是文件名),非必须,可用空''代替; 
  height=100 窗口高度; 
  width=400 窗口宽度; 
  top=0 窗口距离屏幕上方的象素值; 
  left=0 窗口距离屏幕左侧的象素值; 
  toolbar=no 是否显示工具栏,yes为显示; 
  menubar,scrollbars 表示菜单栏和滚动栏。 
  resizable=no 是否允许改变窗口大小,yes为允许; 
  location=no 是否显示地址栏,yes为允许; 
  status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许; 
  </SCRIPT> js脚本结束

(四)服务树的形成

zTree 是一个依靠 jQuery 实现的多功能 “树插件”。优异的性能、灵活的配置、多种功能的组合是 zTree 最大优点。

导入jar包  ztree包
<link rel="stylesheet" th:href="@{ztree/css/zTreeStyle.css}">
<script type="text/javascript" th:src="@{ztree/jquery.ztree.all-3.5.min.js}"></script>
<script type="text/javascript" th:src="@{ztree/jquery.ztree.core-3.2.js}"></script>
<script type="text/javascript" th:src="@{ztree/jquery.ztree.core-3.5.min.js}"></script>
<script type="text/javascript" th:src="@{ztree/jquery.ztree.excheck-3.2.js}"></script>
<script type="text/javascript" th:src="@{ztree/jquery.ztree.excheck-3.5.min.js}"></script>



HTML
<ul id="treeDemo" class="ztree"></ul>

<iframe id="mainContent" name="mainContent1" src="" style="width:100%; height:768px; background-color: #fff; overflow:auto;  float:right;" ></iframe>

<script type="text/javascript">
var setting = {
        data: {
            simpleData: {
                enable: true
            }
        }
    };
     

//请求controller获取数据
$(document).ready(function () {
    jQuery.ajax({
        url: "/saltportal/treeList",
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $.fn.zTree.init($("#treeDemo"), setting, data);
        }
    });
});

//点击节点的onclick事件
function getInfoId(id) {
   $("#mainContent").attr("src","/saltportal/ApplicationPageList?servicecode="+id).children().trigger('click');
}

 //异步刷新tree
var curMenu = null, 
zTree_Menu = null;
var zNodes = [];
function refreshNode(id){
	//获取当前节点
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var nodes = treeObj.getSelectedNodes();
    var selectId = nodes[0].id;
	//重置树
    $.ajax({
        url: "/saltportal/treeList",
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $.fn.zTree.init($("#treeDemo"), setting, data);
            zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
            curMenu = zTree_Menu.getNodes()[0].children[0];
    		zTree_Menu.selectNode(curMenu);
        }
    });
    treeObj.selectNode(selectId, true);
}

</script>

(五)表单数据转换成集合传入

例如:  注释:$("").val();智能获取input框的参数值
前提:<input type="hidden" id="Ass_versionid" name="versionid"/>
function queRequire(id){
	
	var JSONObj=new Object();//为JSON对象  
	var list=[];//生成集合(保存多个商品对象)
	var versionid=null;//保存商品对象  
	//循环将多个商品对象保存到集合中
	for (var i = 0; i<id; i++) {  
		versionid=new Object();//生成一个商品对象
		versionid.versionid=$('#vers'+i).val();//moduleworkload
		list.push(versionid);//保存商品对象到集合中  
	}
	JSONObj.jsonStr=JSON.stringify(list);//将集合转成JSON("jsonStr"用于后台定位)
	$.ajax({
		type: 'GET',
        async: false,
        data: JSONObj,
        url: '/saltportal/version/getVersionAndRequireLists',
        dataType: "json",
        success: function(data){
        	var data = data;
        	var b = data.length;
			$("#Details_list").empty();
        	html='';
    		html+='<table class="table table-striped" style="text-align:left;"><thead><tr><th>版本名称</th><th>需求名称</th></tr></thead>';
    		html+='<tbody>';
    		for (var i = 0; i < data.length; i++) {
    			html+='<td >'+data[i].versionname+'</td>';
        		html+='<td >'+data[i].requirename+'</td>';
        		html+='</tr>';
			}
    		html+='</tbody></table>';
    		if(b == 0){
    			html+='<div style="color:#dd4b39; text-align:center; width:100%;"><span >暂没有版本关联的需求!!!</span></div>';
    		}
        	$("#Details_list").append(html);
        },error:function(){
        	alert("数据加载失败!");
        	Details_version(versionid);
        }
	});
}


后端接收
//关联详情>>单集版本>>(多版本)关联需求查询加载数据
	  @RequestMapping(value="/version/getVersionAndRequireLists" ,method = RequestMethod.GET)
	  @ResponseBody
	  public List<DemandListBean> getVersionAndRequireLists(HttpServletRequest request){
		  List<DemandListBean> list = new ArrayList<DemandListBean>();
		  try {
			  String jsonStr = request.getParameter("jsonStr");
			  System.out.println("我进来了!"+jsonStr);
			  List<DemandListBean> versionids = JSON.parseArray(jsonStr,DemandListBean.class);
			  List<Integer> list2 = new ArrayList<Integer>();
			  for (DemandListBean i: versionids) {
				  list2.add(i.getVersionid());
			  }
			  list = versionService.getVersionAndRequireLists(list2);
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
		  return list;
	  }
//service  
@Override
	public List<DemandListBean> getVersionAndRequireLists(List<Integer> list){
		return versionstatusDao.getVersionAndRequireLists(list);
	}
//xml
<!-- 查询多个版本管理的需求信息 -->
    <select id="getVersionAndRequireLists" parameterType="map" resultType="com.zte.saltportal.model.demand.DemandListBean">
    	select c.statusname, BB.* from (
	    	select vi.versionname,SS.* from 
	    		(SELECT 
	    				A.requireid,
	    				vr.versionid, 
					FROM
						require_info A
					LEFT JOIN 
						version_requirerel vr ON A .requireid = vr.requireid 
					where A.requireid in 
						(select requireid FROM version_requirerel where versionid in 
							<foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
	                			#{item}  
	            			</foreach>
						))SS 
			LEFT JOIN version_info vi ON SS.versionid = vi.versionid)BB
		LEFT JOIN 
			enum_versionstatus c ON BB.status = c.versionstatus
    </select>

知识扩展:
来源:https://blog.csdn.net/qq_32786873/article/details/80280869

《传入数组》
$(document).on('click', '#sendArr', function () {
	var ids = [];
	for(var i=0; i<10; i++){
		ids.push(i);
	}
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: '/test/test/sendArr',
		data: {ids:ids},
		traditional: true,
		success: function (result) {
			console.log(result)
		},
		error: function(data){
		  alert("操作异常");
		}
	});
});


后端:

@PostMapping("/sendArr")
public Map<String,Object> sendArr(String[] ids) {
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("ids", ids);
	return map;

《2传入List集合》

$("#sendList").click(function(){
	var ids = [];
	for(var i=0; i<10; i++){
		ids[i] = i;
	}
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: '/test/test/sendList',
		data: JSON.stringify(ids),
		contentType:"application/json",
		success: function (result) {
			console.log(result)
		},
		error: function(data){
		  alert("操作异常");
		}
	});
});

后端:
@PostMapping("/sendList")
public Map<String,Object> sendList(@RequestBody List<String> ids) {
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("ids", ids);
	return map;
}

(六)bootstrap框架的部分使用

学习网址:https://www.runoob.com/bootstrap/bootstrap-code.html
添加链接描述

(1)选项框的使用:bootstrap-select简单使用

单选框可以输入 引入文件
<link href="/bootstrap-select-1.12.4/dist/css/bootstrap-select.min.css" rel="stylesheet" />
<script src="/bootstrap-select-1.12.4/dist/js/bootstrap-select.min.js"></script>

注意名称class="selectpicker"

没有框架

<label>局点</label>
<div class="form-control" style="padding:0px; border: 0px solid #ccc;">
	<div style="width:16%; float:left;">
		<select name="postname" class="form-control" id="demand_postname" onChange="Change_postname();">
	   	</select>
	</div>
	<div style="width:84%; float:left;">
	     <input type="text" placeholder="--请输入--" class="form-control" name="postname11" id="postname11" th:value="${postname}" >
	</div>
    </div>

//局点选择后,input框显示数据
function Change_postname(){
	var postname = $("#demand_postname").val();
	$("#postname11").attr("value",postname);
}

(2)bootstrap框架 重置选项框方式

普通情况select下

document.getElementById("selectid").options.length = 0; 
    	//对input框重置
    	$("#iRequireChanger_versionname").val("");

*bootstrap-select下拉框对select选项框重置

document.getElementById("version_postname").options.selectedIndex = 0; //回到初始状态
$("#version_postname").selectpicker('refresh');//重置选项框
 类似资料: