js知识整理--工作积累
2025年8月24日大约 7 分钟
关闭当前页面
// 重置window.opener用来获取打开当前窗口的窗口引用
// 这里置为null,避免IE下弹出关闭页面确认框
window.opener = null;
// JS重写当前页面
window.open("", "_self", "");
// 顺理成章的关闭当前被重写的窗口
window.close();
监听div元素变化
change事件,在元素的值发生改变时触发,适用于文本域、textarea、select 。 或调用change()方法时可以监听。所以,我们可以模拟change为非表单元素监听change()事件。
DOMNodeInserted 节点插入
<body>
<div id="container">
</div>
<button type="button" id="btn">add "aaa" for div</button>
<script src="jquery-1.11.3.js"></script>
<script>
function changes(){
alert("changes");
}
$("#btn").click(function() {
$("#container").append("aaa");
});
$("#container").bind("DOMNodeInserted", changes);
</script>
</body>
DOMNodeRemoved 节点移除
添加模拟change事件
<body>
<div id="container">
</div>
<button type="button" id="btn">add "aaa" for div</button>
<script src="jquery-1.11.3.js"></script>
<script>
function changes(){
alert("changes");
}
$("#btn").click(function() {
$("#container").append("aaa").change();
});
$("#container").bind("change", changes);
</script>
</body>
获取从另一个页面通过url传递过来的参数
window.location.search
实时监听属性变化
onpropertychange: IE下,当一个HTML元素的属性改变的时候,都能通过 onpropertychange来即时捕获。onchange在属性值改变时还必须使得当前元素失去焦点(onblur)才可以激活该事件。 在用js脚本改动该元素值时候亦能触发onpropertychange事件。
$("xxx").on("propertychange",function(){
alert("变化了");
})
oninput:是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。
$("xxx").on(" input propertychange",function(){
alert("变化了");
})
onchange: (a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效);(b)当前对象失去焦点(onblur);
$("#input_text").bind("input propertychange",function () {
$("#input_button").val("已经输入了"+$("#input_text").val().length+"个字。。。");
});
提示
注意当由js脚本自动触发的时候也可以用此办法监听改变
$('input').bind('input propertychange', function()
{
console.log($(this).val());
});
$('input').bind('input ', function()
{
console.log($(this).val());
});
重点如果input值改变不能触发
在改变完成后自动添加一个触发就可以了
$('input[name=sta]').trigger('input');
监听js对象值变化
//监听分类选择
Object.defineProperty(GoodsAdd.onceGood,'class_id',
{
get:function()
{
return class_id;
},
set:function(newValue)
{
class_id=newValue;
console.log('set :',newValue);
}
});
//
Object.defineProperties(GoodsAdd.onceGood,
{
class_id:
{
configurable: true,
get: function()
{
console.log('get: ',class_id)
return class_id;
},
set: function(newValue)
{
class_id = newValue;
console.log('set: ',newValue)
}
},
//以此类推
});
通过类名获取的元素自动触发点击事件
var nu = $('.orderDetailLink');
console.log(nu.length);
cn = nu[nu.length-1].textContent;
console.log(nu[nu.length-1]);
nu[nu.length-1].click();
页面刷新
1 history.go(0)
2 location.reload()
3 location=location
4 location.assign(location)
5 document.execCommand('Refresh')
6 window.navigate(location)
7 location.replace(location)
8 document.URL=location.href
自动刷新页面的方法: javascript自动刷新页面方法详解
1.页面自动刷新:把如下代码加入区域中
<meta http-equiv="refresh" content="20">
2页面自动跳转:把如下代码加入区域中
<meta http-equiv="refresh" content="20;url=http://www.jbxue.com">
3.页面自动刷新js版
<script language="JavaScript">
function myrefresh()
{
window.location.reload();
}
setTimeout('myrefresh()',1000); //指定1秒刷新一次
</script>
=========
JS刷新框架的脚本语句
//如何刷新包含该框架的页面用
<script language=JavaScript>
parent.location.reload();
</script>
//子窗口刷新父窗口
<script language=JavaScript>
self.opener.location.reload();
</script> www.jbxue.com
( 或 <a href="javascript:opener.location.reload()">刷新</a> )
//如何刷新另一个框架的页面用
<script language=JavaScript>
parent.另一FrameID.location.reload();
</script>
如果想关闭窗口时刷新或者想开窗时刷新的话,在中调用以下语句即可。
<body onload="opener.location.reload()"> 开窗时刷新
<body onUnload="opener.location.reload()"> 关闭时刷新
<script language="javascript">
window.opener.document.location.reload()
</script>
js提交表单
<form name="unband_list" action="#" method="post" onsubmit="return false;" id="unband_form">
<input class="weui-input" type="text" name="box_number" placeholder="请输入箱号">
</form>
==============================================
$('#unband_form').submit(function(event)
{
//alert('提交');
var box_number = unband_list.box_number.value;
console.log(box_number);
});
js调起打印机
https://blog.csdn.net/wwjoyous/article/details/80881881
打印html带样式
printJS(
{
printable: 'pre_doPrint',
type: 'html',
targetStyles:['*'],
css:['/static/css/house/labeling/lab.print.css'],
});
printJS(
{
printable: 'pre_doPrint', //打印元素的id
type: 'html',
targetStyles:['*'],//表示给所有的标签添加样式
css:['/static/css/house/labeling/lab.print.css'],//要打印样式的css文件路径
});
js批量删除数组元素
console.log('要删除的的键值数组:');
console.log(del_key);
var new_match_data = match_data
if(del_key.length>0)
{
for (var i = del_key.length; i>=0; i--)
{
new_match_data.splice(del_key[i],1);
}
}
match_list.reload(
{
data:new_match_data
});
注意,了解splice()函数是关键 逆向操作就可以成功了;
$.post和$.get发送同步请求
由于$.post() 和 $.get() 默认是 异步请求,如果需要同步请求,则可以进行如下使用:
在$.post()前把ajax设置为同步:$.ajaxSettings.async = false;
在$.post()后把ajax改回为异步:$.ajaxSettings.async = true;
---------------------
$.ajaxSettings.async = false;
$.post("/finance/getLastTimeCard", data, function(result) {
// 请求处理
},"json");
$.ajaxSettings.async = true;
---------------------
js上传图片预览
html
<input id="uploaderInput" type="file" name="img[]" accept="image/*" multiple="">
======
js
==========
$('#uploaderInput').change(function(e)
{
console.log('改变了');
var url = url = window.URL || window.webkitURL || window.mozURL;
var files = e.target.files;
console.log(e.target.files);
var reader = new FileReader();
for(var i = 0;i < files.length; i++)
{
var file = files[i];
if(url)
{
src = url.createObjectURL(file);
}
else
{
src = e.target.result;
}
console.log(src);
var dv = $('<img src="'+ src +'" class="img">');
dv.appendTo('#box');
}
=====
****注意这里得到的src,就可以作为图片预览的地址
js图片上传
<div class="weui-cells weui-cells_form">
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">图片上传</p>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles">
</ul>
<div class="weui-uploader__input-box">
<input id="img" name="img[]" class="weui-uploader__input zjxfjs_file" type="file" accept="image/*" multiple="">
</div>
</div>
</div>
</div>
</div>
</div>
注意:这里 id和name必须保持一致 而且必须都有
====================js==========================
$.ajaxFileUpload(
{
url: '/mobile/upload/upload', //这里是服务器处理的代码
type: 'post',
secureuri: false, //一般设置为false
fileElementId: 'img', // 上传文件的id、name属性名
//dataType: 'json', //返回值类型,一般设置为json、application/json
data: {}, //传递参数到服务器
success: function (data, status)
{ console.log('成功');
console.log(status);
console.log(data);
},
error: function (data, status, e)
{
//alert("错误:上传组件错误,请检察网络!");
console.log('失败!');
console.log(data);
console.log(status);
console.log(e);
}
});
注意 dataTYpe返回是错误,虽然能够上传成功
目前只能得到success 和 error 两种状态 无法得到真正的返回值
需要的插件
<script src="/static/js/ajaxfileupload.js"></script>
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
//var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
var io=document.createElement("iframe");
io.id=frameId;
io.name=frameId;
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
})
js 判断对象中是否含有键
json.hasOwnProperty("key1")