jsp模态框
<script type="text/javascript" src="<%=path %>/jsp/management/js/modalBox.js"></script>
<link rel="stylesheet" type="text/css" href="<%=path %>/jsp/management/css/modalBox.css" media="screen" />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>模态框</title>
<link rel="stylesheet" type="text/css" href="modalBox.css">
</head>
<body>
<!-- 触发按钮 -->
<button id="triggerBtn" >模态框</button>
<!-- 模态框 -->
<div id="myModal" class="modal" >
<div class="modal-content" style="width: 800px">
<div class="modal-header">
<h2>头部</h2>
<span id="closeBtn" class="close">×</span>
</div>
<div class="modal-body">
<p>这是一个模态框!</p>
<p>喜欢就点个赞吧!</p>
<p>这是一个模态框!</p>
<p>喜欢就点个赞吧!</p>
<p>这是一个模态框!</p>
<p>喜欢就点个赞吧!</p>
<p>这是一个模态框!</p>
<p>喜欢就点个赞吧!</p>
<p>这是一个模态框!</p>
<p>喜欢就点个赞吧!</p>
</div>
<div class="modal-footer">
<h3>尾部</h3>
</div>
</div>
</div>
<script type="text/javascript" src="modalBox.js"></script>
</body>
</html>
$(function() {
/*建立模态框对象*/
var modalBox = {};
/*获取模态框*/
modalBox.modal = document.getElementById("myModal");
/*获得trigger按钮*/
modalBox.triggerBtn = document.getElementById("triggerBtn");
/*获得关闭按钮*/
modalBox.closeBtn = document.getElementById("closeBtn");
/*模态框显示*/
modalBox.show = function() {
console.log(this.modal);
this.modal.style.display = "block";
}
/*模态框关闭*/
modalBox.close = function() {
this.modal.style.display = "none";
}
/*当用户点击模态框内容之外的区域,模态框也会关闭*/
modalBox.outsideClick = function() {
var modal = this.modal;
window.onclick = function(event) {
if(event.target == modal) {
modal.style.display = "none";
}
}
}
/*模态框初始化*/
modalBox.init = function() {
var that = this;
this.triggerBtn.onclick = function() {
that.show();
}
this.closeBtn.onclick = function() {
that.close();
}
this.outsideClick();
}
modalBox.init();
})();
/*模态框*/
.modal {
display: none; /* 默认隐藏 */
position: fixed; /* 根据浏览器定位 */
z-index: 1; /* 放在顶部 */
left: 0;
top: 0;
width: 120%; /* 全宽 */
height: 100%; /* 全高 */
overflow: auto; /* 允许滚动 */
background-color: rgba(0,0,0,0.4); /* 背景色 */
}
/*模态框内容*/
.modal-content {
display: flex; /*采用flexbox布局*/
flex-direction: column; /*垂直排列*/
position: relative;
background-color: #fefefe;
margin: 5% 650px auto; /*距顶部5% 水平居中*/
padding: 20px;
border: 1px solid #888;
width: 80%;
animation: topDown 0.4s; /*自定义动画,从模态框内容上到下出现*/
}
@keyframes topDown {
from {top: -300px; opacity: 0}
to {top: 0; opacity: 1}
}
/*模态框头部*/
.modal-header {
display: flex; /*采用flexbox布局*/
flex-direction: row; /*水平布局*/
align-items: center; /*内容垂直居中*/
justify-content: space-between;
}
/*关闭X 样式*/
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover {
color: black;
text-decoration: none;
cursor: pointer;
}
<%-- <!-- 触发按钮 -->
<!-- <button id="triggerBtn">模态框</button> -->
<!-- 模态框 -->
<div id="myModal" class="modal">
<div class="modal-content" style="width: 800px">
<div class="modal-header">
<h2>请选择商品规格</h2>
<span id="closeBtn" class="close">×</span>
</div>
<!-- 规格模态框 -->
<form method="post" id="management-form">
<ul class="clearfix">
<li>
<span>规格名称:</span><input name="name" id=name value="${ name }" type="text" class="span3" placeholder="请输入...">
</li>
<li>
<a href="javascript:psida()" id="177-a"><img src="img/search.png"></a>
</li>
</ul>
</form>
<div class="modal-body">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th><img src="img/th-img.png"/> 类别</th>
<th><img src="img/th-img.png"/> 名称</th>
<th><img src="img/th-img.png"/> 备注</th>
</tr>
</thead>
<tbody id = "171-id">
</tbody>
</div>
<div class="modal-footer">
</div>
</div>
</div>
--%>
$.each(data, function(i, v){
$("<tr><td>"+v.parameters+"</td><td>"+v.name+"</td><td>"+v.remark+"</td></tr>").appendTo(aaaa);
});
父子页面 关闭和传值
//关闭弹窗窗口
$.closeDialog(data);
function getChildDatastr1(data);//父页面方法
/**
* 添加规格弹出窗口
*/
function fn(parameters) {
sessionStorage.setItem("parameters", parameters);
var url = "commodityParametersAction!selectCommodityParametersAndCommodityPage.action?parameters="+parameters;
$.dialog({
url : url,
title : '选择商品规格',
width : 900,
height : 500
});
}
子方法 跳转页面
1. 跳转新页面问题
<a href="index.html" id="ad-15a" target="_parent">
<p id="ad-16p"></p>
</a>
$("#ad-16p").trigger('click'); //子标签驱动父标签 可在不满足条件时;
转成json串
public static String jsonStr(Object str){
JSONObject jsonObj = JSONObject.fromObject(str);
return jsonObj.toString();
}
public static String jsonListStr(List list){
JSONArray jsonObj = JSONArray.fromObject(list);
return jsonObj.toString();
}
String jsonStr = Util.jsonListStr(oneList);//多条
String jsonStr = Util.jsonStr(oneList);//单条
response.getWriter().print(jsonStr);
前台获取时间格式
function getTime() {
var myDate = new Date();
var myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
var myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
var myToday = myDate.getDate(); //获取当前日(1-31)
var myDay = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
var myHour = myDate.getHours(); //获取当前小时数(0-23)
var myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
var mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
var nowTime;
nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + ' ' + fillZero(myHour) + ':' +
fillZero(myMinute) + ':' + fillZero(mySecond) + ' ';
console.log(nowTime);
// $('#time').html(nowTime);
};
function fillZero(str) {
var realNum;
if (str < 10) {
realNum = '0' + str;
} else {
realNum = str;
}
return realNum;
}
通过选择器控制当前行
// input父元素 td, td 后面第一个同辈 td, td下面的所有子辈,然后选择第一个,值
var bbb= $(val).parent().next().children().first().val();
可以吧ajax数据转成json串
console.log(JSON.stringify(data));
这个方法get前端value
String param = commodityParametersVo.getParameters();
String[] params = param.split(",");
commodityParametersVo.setParameters(params[0]);
commodityParametersVo.setSortnumber(params[1]);
<select name="commodityParametersVo.parameters" datatype="s2-2" errormsg="请选择下拉框里的数据" style="float: left">
<option >---请选择---</option>
<option value="商品单位,1" <c:if test="${commodityParametersVo.parameters=='商品单位' }">selected</c:if>>商品单位</option>
<option value="商品规格,2" <c:if test="${commodityParametersVo.parameters=='商品规格' }">selected</c:if>>商品规格</option>
</select>
通过身份证号判断 性别
//通过 身份证号判断男女性别
function getSex(number) {
var sexStr = '';
if (number.length == 18) {
if ((Number(number.substring(number.length - 2,
number.length - 1))) % 2 == 0) {
sexStr = '女';
} else {
sexStr = '男';
}
}
document.getElementById("gender-input").value = sexStr;
}
身份util
package com.sdkj.util;
import org.apache.commons.lang.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Description:身份证号的util
* @Author:
* @Date: Created in 11:26 2019-03-27
* @Modified By:
*/
public class IDCardUtil {
/**
* 15位身份证号
*/
private static final Integer FIFTEEN_ID_CARD=15;
/**
* 18位身份证号
*/
private static final Integer EIGHTEEN_ID_CARD=18;
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
/**
* 根据身份证号获取性别
* @param IDCard
* @return
*/
public static String getSex(String IDCard){
String sex ="";
if (StringUtils.isNotBlank(IDCard)){
//15位身份证号
if (IDCard.length() == FIFTEEN_ID_CARD){
if (Integer.parseInt(IDCard.substring(14, 15)) % 2 == 0) {
sex = "女";
} else {
sex = "男";
}
//18位身份证号
}else if(IDCard.length() == EIGHTEEN_ID_CARD){
// 判断性别
if (Integer.parseInt(IDCard.substring(16).substring(0, 1)) % 2 == 0) {
sex = "女";
} else {
sex = "男";
}
}
}
return sex;
}
/**
* 根据身份证号获取年龄
* @param IDCard
* @return
*/
public static Integer getAge(String IDCard){
Integer age = 0;
Date date = new Date();
if (StringUtils.isNotBlank(IDCard)&& isValid(IDCard)){
//15位身份证号
if (IDCard.length() == FIFTEEN_ID_CARD){
// 身份证上的年份(15位身份证为1980年前的)
String uyear = "19" + IDCard.substring(6, 8);
// 身份证上的月份
String uyue = IDCard.substring(8, 10);
// 当前年份
String fyear = format.format(date).substring(0, 4);
// 当前月份
String fyue = format.format(date).substring(5, 7);
if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
// 当前用户还没过生
} else {
age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
}
//18位身份证号
}else if(IDCard.length() == EIGHTEEN_ID_CARD){
// 身份证上的年份
String year = IDCard.substring(6).substring(0, 4);
// 身份证上的月份
String yue = IDCard.substring(10).substring(0, 2);
// 当前年份
String fyear = format.format(date).substring(0, 4);
// 当前月份
String fyue = format.format(date).substring(5, 7);
// 当前月份大于用户出身的月份表示已过生日
if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) {
age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
// 当前用户还没过生日
} else {
age = Integer.parseInt(fyear) - Integer.parseInt(year);
}
}
}
return age;
}
/**
* 获取出生日期 yyyy年MM月dd日
* @param IDCard
* @return
*/
public static String getBirthday(String IDCard){
String birthday="";
String year="";
String month="";
String day="";
if (StringUtils.isNotBlank(IDCard)){
//15位身份证号
if (IDCard.length() == FIFTEEN_ID_CARD){
// 身份证上的年份(15位身份证为1980年前的)
year = "19" + IDCard.substring(6, 8);
//身份证上的月份
month = IDCard.substring(8, 10);
//身份证上的日期
day= IDCard.substring(10, 12);
//18位身份证号
}else if(IDCard.length() == EIGHTEEN_ID_CARD){
// 身份证上的年份
year = IDCard.substring(6).substring(0, 4);
// 身份证上的月份
month = IDCard.substring(10).substring(0, 2);
//身份证上的日期
day=IDCard.substring(12).substring(0,2);
}
birthday=year+"年"+month+"月"+day+"日";
}
return birthday;
}
/**
* 身份证验证
* @param id 号码内容
* @return 是否有效
*/
public static boolean isValid(String id){
Boolean validResult = true;
//校验长度只能为15或18
int len = id.length();
if (len != FIFTEEN_ID_CARD && len != EIGHTEEN_ID_CARD){
validResult = false;
}
//校验生日
if (!validDate(id)){
validResult = false;
}
return validResult;
}
/**
* 校验生日
* @param id
* @return
*/
private static boolean validDate(String id)
{
try
{
String birth = id.length() == 15 ? "19" + id.substring(6, 12) : id.substring(6, 14);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date birthDate = sdf.parse(birth);
if (!birth.equals(sdf.format(birthDate))){
return false;
}
}
catch (ParseException e)
{
return false;
}
return true;
}
}
打印
//打印
function print(){
$("#printdivaa").jqprint({
debug: false,
importCSS: true,
printContainer: true,
operaSupport: false
});
}
//包裹住打印的内容
<div id='printdivaa'></div>
jquery.jqprint-0.3 引入这个js
jquery.jqprint-0.3
// -----------------------------------------------------------------------
// Eros Fratini - eros@recoding.it
// jqprint 0.3
//
// - 19/06/2009 - some new implementations, added Opera support
// - 11/05/2009 - first sketch
//
// Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
// requires jQuery 1.3.x
//
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//------------------------------------------------------------------------
(function($) {
var opt;
$.fn.jqprint = function (options) {
opt = $.extend({}, $.fn.jqprint.defaults, options);
var $element = (this instanceof jQuery) ? this : $(this);
if (opt.operaSupport && $.browser.opera)
{
var tab = window.open("","jqPrint-preview");
tab.document.open();
var doc = tab.document;
}
else
{
var $iframe = $("<iframe />");
if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }
$iframe.appendTo("body");
var doc = $iframe[0].contentWindow.document;
}
if (opt.importCSS)
{
if ($("link[media=print]").length > 0)
{
$("link[media=print]").each( function() {
doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
});
}
else
{
$("link").each( function() {
doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
});
}
}
if (opt.printContainer) { doc.write($element.outer()); }
else { $element.each( function() { doc.write($(this).html()); }); }
doc.close();
(opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
}
$.fn.jqprint.defaults = {
debug: false,
importCSS: true,
printContainer: true,
operaSupport: true
};
// Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
jQuery.fn.outer = function() {
return $($('<div></div>').html(this.clone())).html();
}
})(jQuery);
校验日期
if (dataA != null && !"".equals(dataA)) {
param = param + " and a.data >= '" + dataA + " 00:00:01'";
}
if (dataB != null && !"".equals(dataB)) {
param = param + " and a.data <= '" + dataB + " 23:59:59'";
}
删除数组拼接最后一个逗号
String[] id = request.getParameterValues("id");
String ids = "";
for (int i = 0; i < id.length; i++) {
ids += "'"+ id[i] + "',";
}
//查找最后一个逗号
int count = ids.lastIndexOf(",");
if(count!=-1){
ids = ids.substring(0,count)+ids.substring(count+1,ids.length());
将1,1,1前台字符串拼接'1','1','1'样
function dc(){
var id = [];
$('input[name="selectFlag"]:checked').each(function(){
id.push($(this).val());
});
if(id.length==0){
alert('请先勾');
return id;
}
$('#listform').attr("action","officeAction!dc.action?id="+id);
$('#listform').submit();
}
//controller
String id = request.getParameter("id");
officeService.selectAllDC(id.split(","));
//impl
String sql = "select * from office where id in ('"+StringUtils.join(id,"','")+"')";
用appent的时候 传值可以转义
tr(\''+id+'\')"
返回上一页并刷新
//A页面
window.addEventListener('pageshow', function(event) {
if(event.persisted) { // ios 有效, android 和 pc 每次都是 false
location.reload();
} else { // ios 除外
if(sessionStorage.getItem('refresh') === 'true') {
location.reload();
}
}
sessionStorage.removeItem('refresh');
});
//B页面 写在修改的跳转的ajax里面
sessionStorage.setItem("refresh","true");
window.history.go(-1);
上传图片
vo
public class UploadFileVo {
private String cf_id;
private String c_id;
private String cf_name;
private String cf_url;
private String cf_type;
private String category;
private String stateid;//20191211 fcl
}
set/get
maps
//操作这几个数据即可
(cf_id,c_id,cf_name,cf_url
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace ="uploadFileAA" >
<typeAlias alias="uploadFileVoAA" type="com.sdkj.licence.vo.UploadFileVo" />
<!-- 添加 图片-->
<insert id="insertUploadFileAA" parameterClass="uploadFileVoAA">
insert
into
uploadfile
(cf_id,c_id,cf_name,cf_url,cf_type)
values
(#cf_id#,#c_id#,#cf_name#,#cf_url#,#cf_type#)
</insert>
<!-- 通过ID获取一条数据 -->
<select id="selectByUploadFileIdAA" parameterClass="java.lang.String"
resultClass="uploadFileVoAA">
select *
from uploadfile
where c_id=#c_id#
</select>
<!-- 通过项目idID和Type获取一条数据 -->
<select id="selectByUploadFileIdAndType" parameterClass="java.lang.String"
resultClass="uploadFileVoAA">
$value$
</select>
<!-- 删除 -->
<delete id="deleteUploadFileIdAA" parameterClass="java.lang.String">
delete
from uploadfile where c_id=#c_id#
</delete>
<!-- 删除 -->
<delete id="deleteUploadFileIdAndType" parameterClass="java.lang.String">
$value$
</delete>
</sqlMap >
server/impl
// 添加
//修改的话 先删除在添加
/**
package com.sdkj.licence.service;
import java.util.List;
import com.sdkj.lable.vo.LableVo;
import com.sdkj.licence.vo.UploadFileVo;
import com.sdkj.util.context.Pagination;
public interface UploadFileService {
// 添加
// 修改的话 先删除在添加
/**
* 上传图片
*
* @param UploadFileVo
* 实体类
* @return
* @throws Exception
*/
public void insertUploadFileAA(UploadFileVo uploadFileAVo) throws Exception;
// 可以用查询一条集合都可以
/**
* 通过主键获取详细信息
*
* @param id
* 主键
* @return 返回一条数据
* @throws Exception
*/
public List selectByUploadFileIdAA(String id) throws Exception;
/**
* 删除这条信息
*
* @param id
* 主键
* @return 返回一条数据
* @throws Exception
*/
public void deleteUploadFileIdAA(String id) throws Exception;
/**
* 通过项目id和Type获取一条数据 -
*
* @param id
* 主键
* @return 返回一条数据
* @throws Exception
*/
public List selectByUploadFileIdAndType(String xmid,String type) throws Exception;
/**
* 删除这条信息
*
* @param id
* 主键
* @return 返回一条数据
* @throws Exception
*/
public void deleteUploadFileIdAndType(String xmid,String type) throws Exception;
}
impl
package com.sdkj.licence.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sdkj.lable.vo.LableVo;
import com.sdkj.licence.service.UploadFileService;
import com.sdkj.licence.vo.UploadFileVo;
import com.sdkj.util.basic.dao.Dao;
import com.sdkj.util.context.Pagination;
@Service
public class UploadFileServiceaImpl implements UploadFileService {
@Autowired
private Dao dao;
public void insertUploadFileAA(UploadFileVo uploadFileVo) throws Exception {
dao.update("insertUploadFileAA", uploadFileVo);
}
public List selectByUploadFileIdAA(String id) throws Exception {
return dao.queryForList("selectByUploadFileIdAA",id);
}
public void deleteUploadFileIdAA(String id) throws Exception {
dao.update("deleteUploadFileIdAA", id);
}
public List selectByUploadFileIdAndType(String xmid,String type) throws Exception {
String param = "";
if (xmid != null && !"".equals(xmid) && type != null && !"".equals(type)) {
param = "select * from uploadfile where c_id like '%" + xmid + "%' and cf_type like '%" + type + "%' ";
}
return dao.queryForList("selectByUploadFileIdAndType",param);
}
public void deleteUploadFileIdAndType(String xmid, String type) throws Exception {
String param = "delete from uploadfile where c_id='"+xmid+"' and cf_type = '"+type+"' ";
dao.update("deleteUploadFileIdAndType", param);
}
}
action
//后台获图片信息
String[] fileName=request.getParameterValues("fileName");
String[] filePath=request.getParameterValues("filePath");
String[] fileType=request.getParameterValues("fileType");
if (id != null && !"".equals(id)) {
uploadFileService.deleteUploadFileIdAA(xmid);
if (null != fileName && 0 != fileName.length) {
for (int i = 0; i < fileName.length; i++) {
uploadFileAVo = new UploadFileVo();
uploadFileAVo.setCf_id(CommonFunc.getGUID());
uploadFileAVo.setC_id(xmid);
uploadFileAVo.setCf_name(fileName[i]);
uploadFileAVo.setCf_url(filePath[i]);
uploadFileAVo.setCf_type(fileType[i]);
uploadFileService.insertUploadFileAA(uploadFileAVo);
}
}
}
<tr>
<th>国有土地使用证:</th>
<td colspan="3" width="275" height="40" align="left" valign="left">
<div align="left">
<span onclick="addFileUpload('gytdsyzid','国有土地使用证')" class="btn btn-small btn-info"
style="color: #FFFFFF; font-weight: bold;">添加文件</span>
</div>
<table id="gytdsyzid" style="margin-top: 8px;"
class="table2">
<c:forEach var="m" items="${UploadFile}">
<c:if test="${m.cf_type == '国有土地使用证'}">
<tr id="${m.cf_id }">
<td><div align="left">
<a href="http://<%=request.getServerName()%>:<%=request.getServerPort() %>/download/${m.cf_name }"
target="_bank"> <img
src="http://<%=request.getServerName()%>:<%=request.getServerPort() %>/download/${m.cf_name }"
style="width: 200px; height: 100px;" />
</a>
</div></td>
<td><input type="button" value="删除"
onclick="delFile('${m.cf_id }',this);" style="width: 50px;" />
</td>
<input type="hidden" name="fileName" value="${m.cf_name }" />
<input type="hidden" name="filePath" value="${m.cf_url }" />
<input type="hidden" name="fileType" value="${m.cf_type }" />
</tr>
</c:if>
</c:forEach>
</table>
</td>
</tr>
var fileSum=1;
var tupian;
var type;
function addFileUpload(table,count){
if(fileSum == 5){
$.alert("最多只能同时上传5个文件!");
return;
}
fileSum = fileSum+1;
$('#'+table).append('<tr><td width="100px"><label>文件名称:</label></td><td><input id="myFile_'+fileSum+'" type="file" name="myFile_'+fileSum+'"/></td></tr>');
}
function addFileUpload(table,count){
tupian = table;
type=count;
$.dialog({
id:'uploadFilesId',
url:'filesUpload!uploadFilesg.action',
title: '上传文件',
width: 500,
height: 200,
data:{
filePath:'C:/download/'
}
});
}
function getChildData1(data){
//上传附件需要用到的
var json = $.parseJSON(data);
$(json.files).each(function(){
$('#'+tupian).append(
"<tr><td><div align='left'><a href=http://<%=request.getServerName()%>:<%=request.getServerPort() %>/download/"+this.name+" target='_bank' class='input1' ><img src='http://<%=request.getServerName()%>:<%=request.getServerPort() %>/download/"+this.name+"' style='width: 200px; height: 100px;' /></a><input type='hidden' value="+type+" name='fileType'/><input type='hidden' value='"+this.name+"' name='fileName'/>"+
"<input type='hidden' name='filePath' value='"+this.realPath+"'/></td><td><input type='button' value='删除' onclick='javascript:$(this).parent().parent().remove()' style='width:50px;'/></div></td></tr>");
})
}
function delFile(pf_id,btn){
$("tr[id="+pf_id+"]").remove();
}
-需要批量删除的时候通过type判断
@Transactional(rollbackFor = Exception.class)
public void deleteFdcLicence(String ids,String xmids) {
try {
String[] temp = ids.split(",");
String[] tempa = xmids.split(",");
String type = "国有土地使用证,建设用地规划许可证,建设工程规划许可证,建筑工程施工许可证,商品房预售许可证,商品房销售许可证";
String[] tempas = type.split(",");
for (int i = 0; i < temp.length; i++) {
if (null != temp[i] && !"".equals(temp[i])) {
String id = temp[i];
String xmid = tempa[i];
for (int j = 0; j < tempas.length; j++) {
uploadFileService.deleteUploadFileIdAndType(xmid,tempas[j]);
}
dao.delete("deleteFdcLicence", id);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
oracle字符串拼接
substr((sum(xiaoji)-sum(jinhuoxiaoji))/sum(xiaoji),2,2)||'.'||substr((sum(xiaoji)-sum(jinhuoxiaoji))/sum(xiaoji),4,2) as lirunlv
如果当前选中的值和后端传的一样就固定
$.each(data, function(i, v){
if(v.riqi=='${riqi}'){
$("<option selected >"+v.riqi +"</option>").appendTo(riqiIpt);
}else{
$("<option >"+v.riqi +"</option>").appendTo(riqiIpt);
}
});
js foreach 停止
//全局变量判断
var result = true;
//循环判断有没有空串
$(".purchase_count-td").each(function(){
if($(this).val()==""){
alert("请填写数量")
result = false;
return false;
}else{result = true;}
});
if (!result){
return false;
}
集合booler比较
String zbid = request.getParameter("zbid");
String [] s = zbid.split(",");
for(int i=0;i<list.size();i++){
if(Arrays.asList(s).contains(((LableStandardVo)list.get(i)).getId())){
((LableStandardVo)list.get(i)).setCheck("true");
}
}
数据比较 appendTo
success:function(data){
$.each(data, function(i, v){
$('input[name="id-ipt"]').each(function(){
if(v.zbid == this.value ){
$('<label ><input id='+ v.id +' value='+v.id +' style="width: 20px;float: left ;margin-top: 2px;" type="checkbox" size="50" />').appendTo($(this).next());
$('<span style="float:left;">'+ v.bqname +'</span></label>').appendTo($(this).next());
}
});
});
//console.log(data);
}
字符串干掉最后一位
$('<label ><input id='+ v.id +' value='+v.id +'#'+v.zbid+' style="width: 20px;float: left ;margin-top: 2px;" class = "bqid" name = "bqid'+this.value+'" type="checkbox" size="50" />').appendTo($(this).next());
js
//获取选中的集合标签
var bqid = "";
$('input[class="bqid"]:checked').each(function(){
bqid=bqid+$(this).val()+",";
});
$("#bqidList").val(bqid);
//from 表单提交
<input id="bqidList" name="bqidList" value="" type="hidden" />
bqids=bqids.substring(0,bqids.length()-1);
String[] bqid = bqids.split(",");
//添加标签评价记录中间表 外部循环一次,内部循环比较次数
for (String string : bqid) {
lableDefatilVo.setId(CommonFunc.getGUID());
if(string.split("#")[1].equals(Ids[i])){
lableDefatilVo.setLableid(string.split("#")[0]);
lableDefatilVo.setDetailid(result);
lableDefatilVo.setResult("1");
lableDefatilService.insertLableDefatil(lableDefatilVo);
}
}
from表单序列号传值
<!--table-->
<form aciont="" method="post" name="listform" id="listform">
<input type= "hidden" id="news-ipt" name= "news"/>
<input type= "hidden" id="sendperson-ipt" name= "sendperson"/>
<div id = "div-id">
</div>
</from>
var qyid = [];
var receivedept = [];
$('input[name="selectFlag"]:checked').each(function(){
qyid.push($(this).val());
receivedept.push($(this).parent().next().next().next().text());
$("#div-id").append("<input type= 'hidden' value = '"+ $(this).val() +"' name= 'qyid'/> ")
$("#div-id").append("<input type= 'hidden' value = '"+ $(this).parent().next().next().next().text() +"' name= 'receivedept'/> ")
});
if(qyid.length==0){
alert('请先选择一条数据');
return defatilid;
}
//表单外的值传入表单中
$("#news-ipt").val($("#news-id").val());
$("#sendperson-ipt").val($("#sendperson-id").val());
删除tr
<tr>
<td> <a style="width:50px;" href="#" onclick="javascript:$(this).parent().parent().remove()"><img src="img/t-delete.png"></a> </td>
</tr>
数组 in 查询
public List selectLableAndCredit(String[] zbid) throws Exception {
String count = "";
for (int i = 0; i < zbid.length; i++) {
count = count + zbid[i] + ",";
}
String sql = "select a.zbid as zbid,b.id,b.bqname from bq_lable_zb a left join bq_lable b on a.lableid = b.id where a.zbid in ('"
+ StringUtils.join(count.split(","), "','") + "')";
//System.out.println("yap="+sql);
return dao.queryForList("selectLableAndCredit", sql);
三级联动
var provinces =['山西','山东','河南','河北'];
var cities = [
['太原','晋中','大同','阳泉'],
['济南','青岛','威海'],
['郑州','洛阳'],
['石家庄','保定']
];
var areas = [
[
['小店','迎泽','杏花岭','尖草坪'],
['榆次','左权','寿阳'],
['左云'],
['平定','盂县']
],
[
['章丘','天桥'],
['黄岛','城阳'],
['环翠区','文登区'],
],
[
['中原','上街'],
['洛龙','吉利'],
],
[
['新华','桥西'],
['清苑','徐水'],
],
]
<script>
//html元素全部加载完毕执行
/*$(document).ready(function () {
})*/
$(function () {
//遍历有哪些省
$(provinces).each(function(i,o){ //i获得省的下标,o对应的值
var str = "<option value=\""+i+"\">"+o+"</option>";
$('#province').append(str);
});
$('#province').on('change',function () { //选中省之后,添加事件
pIndex = $('#province').find(':selected').attr('value'); //获得选中省的下标
$('#city').empty().append("<option value=\"\">请选择</option>");
$('#area').empty().append("<option value=\"\">请选择</option>");
$(cities[pIndex]).each(function (i,o) {
var str = "<option value=\""+i+"\">"+o+"</option>";
$('#city').append(str);
});
});
$('#city').on('change',function(){
cIndex = $('#city').find(':selected').attr('value');
$('#area').empty().append("<option value=\"\">请选择</option>");
$(areas[pIndex][cIndex]).each(function(i,o){
var str = "<option value=\""+i+"\">"+o+"</option>";
$('#area').append(str);
})
});
});
</script>
</head>
<body>
<select name="" id="province">
<option value="">请选择</option>
</select>省
<select name="" id="city">
<option value="">请选择</option>
</select>市
<select name="" id="area">
<option value="">请选择</option>
</select>县
</body>
清除缓存
oracle去重
DISTINCT(a.id)
下载
<!-- 1、通过点击按钮,直接将PDF文件在页面中打开进行阅读 -->
<a href="../../pdfExplain/车辆系统人员画像评分标准.pdf" class="sel_btn" download>点击下载人员画像评价办法</a>
<!-- 2、通过点击按钮,直接将PDF文件政教到本地,然后可打开进行阅读 -->
<input type="hidden" id="downPDF"><!-- 隐藏域:存放处室名字,供下载PDF作判断 -->
<a href="#" class="sel_btn" id="links" download onClick="downPDF();">点击下载人员画像评价办法</a>
// xxx系统人员画像评价办法PDF下载 2018 05 24
function downPDF(){
var pdf = $("#downPDF").val();
if(pdf.indexOf("车辆") != -1){
document.getElementById('links').href = "../../pdfExplain/车辆系统人员画像管理办法和评分标准.pdf";
} else if(pdf.indexOf("工务") != -1){
document.getElementById('links').href = "../../pdfExplain/工务系统人员画像管理办法和评分标准.pdf";
}
}
关于js禁止浏览器缩放
//前段时间由于工作需要,需要实现禁止使用Ctrl/Command + -/+, 以及Ctrl/Command + 鼠标滚动等方式缩放浏览器:
$(document).keydown(function (event) {
//event.metaKey mac的command键
//mac下chrome: - 189, + 187 firefox: - 173, + 61,
//数字键盘: + 107, - 109
if ((event.ctrlKey === true || event.metaKey === true)&&
(event.which === 189 || event.which === 187
|| event.which === 173 || event.which === 61
|| event.which === 107 || event.which === 109))
{
event.preventDefault();
}
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
if (event.ctrlKey === true || event.metaKey) {
event.preventDefault();
}
});
//然而最近升级了chrome浏览器到73,再运行项目的时候突然报错:
//查看了相关说明,发现chrome73为了减少用户触摸屏幕后更新显示所需的时间,将在文档级目标(窗口)上注册的wheel/mousewheel事件侦听器默认为passive(即:{passive: true})。而这样的设置将忽略此类侦听器内部的preventDefault()调用,从而使chrome下的禁止功能失效。目前先根据官方说明做了修改:
window.addEventListener('mousewheel', function(event){
if (event.ctrlKey === true || event.metaKey) {
event.preventDefault();
}
},{ passive: false});
//firefox
window.addEventListener('DOMMouseScroll', function(event){
if (event.ctrlKey === true || event.metaKey) {
event.preventDefault();
}
},{ passive: false});
关于触摸屏放大缩小
document.addEventListener('touchstart', function(event) {
if (event.touches.length > 1) {
event.preventDefault()
}
}, { passive: false, capture: false });
保存前是否确定
var msg = "您真的确定要删除吗?\n\n请确认!";
if (confirm(msg)==true){
return true;
}else{
return false;
}
自增 001 002
public static void main(String[] args) {
int number = 002 ;
NumberFormat numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMinimumIntegerDigits(3);
numberFormat.setGroupingUsed(false);
for (int time = 0 ; time < 10; time++){
number++;
String s = numberFormat.format(number);
System.out.println(s);
number = Integer.parseInt(s);
}
}
js计算时间
<script type="text/javascript">
var date1= '2015/05/01 00:00:00'; //开始时间
var date2 = new Date(); //结束时间
var date3 = date2.getTime() - new Date(date1).getTime(); //时间差的毫秒数
//------------------------------
//计算出相差天数
var days=Math.floor(date3/(24*3600*1000))
//计算出小时数
var leave1=date3%(24*3600*1000) //计算天数后剩余的毫秒数
var hours=Math.floor(leave1/(3600*1000))
//计算相差分钟数
var leave2=leave1%(3600*1000) //计算小时数后剩余的毫秒数
var minutes=Math.floor(leave2/(60*1000))
//计算相差秒数
var leave3=leave2%(60*1000) //计算分钟数后剩余的毫秒数
var seconds=Math.round(leave3/1000)
alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
</script>
传值 传的是String
public String sendPost(){
HttpClient client = new HttpClient(); //创建Client
PostMethod method=null;
String result="";
try {
method = new PostMethod("地址");
method.setParameter("token",accessToken.getAccessToken() );// 设置参数
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {// 响应成功
result = method.getResponseBodyAsString();// 调用返回结果
return result;
} else {// 不成功组装结果
return "error";
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
接json 接口
public Map<String,Object> getString() throws Exception{
System.out.println("进入=====================");
//后台接收
InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8");
char [] buff=new char[1024];
int length=0;
while((length=reader.read(buff))!=-1){
String x=new String(buff,0,length);
System.out.println(x);
}
//响应
Map<String,Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
return jsonObject;
}
给json接口传数据
String json = "{czrzh:\""+czrzh+"\","
+ "zzbm:\""+zzbm+"\","
+ "czr:\""+czr+"\","
+ "fzjg:\""+fzjg+"\","
+ "fzrq:\""+fzrq+"\","
+ "zzcyztlx:\""+zzcyztlx+"\","
+ "zzyxrqks:\""+zzyxrqks+"\","
+ "zzyxrqjs:\""+zzyxrqjs+"\","
+ "xkzbh:\""+xkzbh+"\","
+ "qymc:\""+qymc+"\","
+ "djzcdz:\""+djzcdz+"\","
+ "fddbrxm:\""+fddbrxm+"\","
+ "jylb:\""+jylb+"\","
+ "jyqy:\""+jyqy+"\","
+ "xkzyxqxq:\""+xkzyxqxq+"\","
+ "xkzyxqx:\""+xkzyxqx+"\"}";
public static String post(String actionUrl, String params, String username, String insid)
throws IOException {
String serverURL = actionUrl;
StringBuffer sbf = new StringBuffer();
String strRead = null;
URL url = new URL(serverURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");//请求post方式
connection.setDoInput(true);
connection.setDoOutput(true);
//header内的的参数在这里set
//connection.setRequestProperty("key", "value");
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
//body参数放这里
writer.write(params);
writer.flush();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
connection.disconnect();
String results = sbf.toString();
//通过传值 获取data
JSONObject jsonObject = new JSONObject().parseObject(results);
String data = jsonObject.getString("data");
// one one = new one(urlSeal);
// System.out.println(one);
//通过data获取urlSeal
// ;
// return results;
return getUrlSeal(data,username,insid);
// return data;
}
通过周获取 日期
public static void main(String[] args) {
System.out.println(getTheSpecifiedYearAndWeekDate("202301").get("fisrstDay"));
System.out.println(getTheSpecifiedYearAndWeekDate("202301").get("lastDay"));
}
/**
* 输入 年+周数能算出 这周几号到几号 202243 2022-10-11 到 2022-10-18
* @param date
* @return
*/
public static Map<String,String> getTheSpecifiedYearAndWeekDate(String date) {
date = date.replace("-", "");
Integer year = Integer.valueOf(date.substring(0, 4));
Integer week = Integer.valueOf(date.substring(4, 6));
Map<String,String> timeMap=new HashMap();
Calendar calendar = Calendar.getInstance();
calendar.set(year, 0, 1);
int zhouji=calendar.get(Calendar.DAY_OF_WEEK);
// System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
//计算当年第一周还剩几天
int dayOfWeek = 0;
if (1==zhouji){
dayOfWeek=1;
}
if (2==zhouji){
dayOfWeek=7;
}
if (3==zhouji){
dayOfWeek=6;
}
if (4==zhouji){
dayOfWeek=5;
}
if (5==zhouji){
dayOfWeek=4;
}
if (6==zhouji){
dayOfWeek=3;
}
if (7==zhouji){
dayOfWeek=2;
}
// System.out.println(dayOfWeek);
if(dayOfWeek>3){
week = week -2;
}else {
week = week -1;//周数减去第一周再减去要得到的周
}
calendar.add(Calendar.DAY_OF_YEAR, week *7+dayOfWeek);
timeMap.put("fisrstDay",new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_YEAR, 6);
timeMap.put("lastDay",new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
return timeMap;
}
计算两个日期之间的天数
/**
*计算两个日期之间的天数
*@param startDate
*@param endDate
*@return 天数
*/
public static Integer daysBetween(String startDate,String endDate) throws Exception{
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sd.parse(startDate));
long time1 = cal.getTimeInMillis();
cal.setTime(sd.parse(endDate));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
是苹果或者安卓手机就能进入
//是苹果或者安卓手机就能进入
public String indexOf(String urls) {
String userAgent = request.getHeader("user-agent");
String url = "";
if ((userAgent.indexOf("Android") != -1) ) {
url= ""+urls;
} else if((userAgent.indexOf("iPhone") != -1)) {
url= ""+urls;
}
return url;
}
去掉周六周日的 后5天
var weekday=["周日","周一","周二","周三","周四","周五","周六"];
var arr=[];
var dateTime=new Date();
dateTime=dateTime.setDate(dateTime.getDate()+1);
var date=new Date(dateTime);
var oneDayLong = 24*60*60*1000 ;
var num=0;
for (var i=0;i<weekday.length;i++){
var nowTime = date.getTime() ;
nowTime=nowTime+oneDayLong*i;
num=new Date(nowTime).getDay();
// console.log(num);
if(num!=0&&num!=6){
arr[weekday[num]]=(new Date(nowTime).getMonth()+1)+"/"+new Date(nowTime).getDate();
}
}
for (var i in arr){
console.log(i+":"+arr[i]);
}
前面补0
int num=6;
DecimalFormat decimalFormat = new DecimalFormat("000000");
String numFormat= decimalFormat .format(num);
System.out.println(numFormat);//打印结果"000006"}
纵向循环
<tr>
<c:forEach items="${list}" var="m" varStatus="stauts">
<td>
<table>
<tbody>
<tr>
<td>${stauts.count}</td>
</tr>
<tr>
<td>${m.}</td>
</tr>
<tr>
<td>${m. }</td>
</tr>
<tr>
<td>${m. }</td>
</tr>
<tr>
<td>111</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
</td>
</c:forEach>
</tr>
表头固定
<style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; border: 1px solid #ddd; } th { position: sticky; top: 0; background-color: #f2f2f2; } </style>
checkbox选一个
<form class="layui-form" action="" style="margin: 50px auto;">
<div class="layui-form-item">
<div class="layui-input-block">
<input type="checkbox" name="check" value="1" title="参考" lay-filter="filterName"/>
<input type="checkbox" name="check" value="0" title="不参考" lay-filter="filterName"/>
</div>
</div>
</form>
layui.use('form', function () {
var form = layui.form();
form.on('checkbox(filterName)', function (data){
var val = data.value;
//如果checkbox的值不等于选中的checkbox的值则移出选中状态
$(":checkbox[name='check'][value!='" + val + "']").removeAttr('checked');
form.render();
})
})
借助Map来获取listA、listB的不同元素集合
/**
* 借助Map来获取listA、listB的不同元素集合
*
* @param listA 集合A
* @param listB 集合B
* @return list<String> 不同元素集合
*/
public static List<String> getDifferListByMap(List<String> listA, List<String> listB) {
List<String> differList = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
long beginTime = System.currentTimeMillis();
for (String strA : listA) {
map.put(strA, 1);
}
for (String strB : listB) {
Integer value = map.get(strB);
if (value != null) {
map.put(strB, ++value);
continue;
}
map.put(strB, 1);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
//获取不同元素集合
if (entry.getValue() == 1) {
differList.add(entry.getKey());
}
}
long endTime = System.currentTimeMillis();
System.out.println("集合A和集合B不同的元素:"+differList);
System.out.println("使用map方式遍历, 对比耗时: " + (endTime - beginTime)+"毫秒。");
return differList;
}
两个或者多个List合并的时候增加效率
//根据项目ID查询项目下所有建设工人信息以及出勤天数
List<ProjectDatasVo> list = checkWorkService.queryPeopleManageInOutXQXQ(dataA,dataB,id,peoplename,workstate);
List<ProjectDatasVo> queryPeopleManageInOutA = checkWorkService.queryPeopleManageInOutA(id);
List<ProjectDatasVo> queryPeopleManageInOutAA = checkWorkService.queryPeopleManageInOutAA(id);
Map<String, ProjectDatasVo> maps = new HashMap<>();
// 将列表2中的数据存储到哈希表中,使用共同的属性作为键
for (ProjectDatasVo projectDatasVo : queryPeopleManageInOutA) {
maps.put(projectDatasVo.getIdCard(), projectDatasVo);
}
Map<String, ProjectDatasVo> mapss = new HashMap<>();
// 将列表3中的数据存储到哈希表中,使用共同的属性作为键
for (ProjectDatasVo projectDatasVo : queryPeopleManageInOutAA) {
mapss.put(projectDatasVo.getIdCard(), projectDatasVo);
}
// 遍历列表1,通过哈希表查找匹配的对象并进行关联
for (ProjectDatasVo listA : list) {
ProjectDatasVo matchedObj2 = maps.get(listA.getIdCard());
ProjectDatasVo matchedObj22 = mapss.get(listA.getIdCard());
if (matchedObj2 != null) {
// 执行关联操作
listA.setPid(matchedObj2.getPid());
listA.setCqday(matchedObj2.getCqday());
}
if (matchedObj22 != null) {
// 执行关联操作
listA.setCounts(matchedObj22.getCounts());
listA.setWorkstate(matchedObj22.getWorkstate());
}
}