Ai
1 Star 0 Fork 0

中国好程序员/common-web

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
common.js 20.09 KB
一键复制 编辑 原始数据 按行查看 历史
中国好程序员 提交于 2025-12-07 14:14 +08:00 . inputs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
/*---------function-----------*/
//加入收藏
function addFavorite() {
try {
window.external.addFavorite(window.location, document.title);
} catch (e) {
try {
window.sidebar.addPanel(document.title, window.location, "");
} catch (e) {
alert("你的浏览器不支持自动加入收藏 请按Ctrl+D键加入收藏");
}
}
}
function base64Encode(blob, callback) {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
callback(e.target.result);
}
}
function base64Decode(str) {
//str不带声明
var byteString = atob(str);
var uint8Array = new Uint8Array(byteString.length);
for (var index = 0; index < byteString.length; index++) {
uint8Array[index] = byteString.charCodeAt(index);
}
return uint8Array;
}
//检查是否是图片
function isImage(url) {
return url.substring(url.lastIndexOf(".")).toLowerCase().match(/.png|.jpg|.jpeg/);
}
//字符串填充
function stringFormat() {
var args = arguments;
return args[0].replace(/\{(\d+)\}/g, function (m, i) {
return args[i * 1 + 1];
});
}
//log
function log() {
var args = arguments;
var msg = args[0].replace(/\{(\d+)\}/g, function (m, i) {
return args[i * 1 + 1];
});
$("#log").log(msg);
}
function notNull(value) {
return value == undefined || value == '' ? 'default' : value;
}
//页面跳转
function relocate(url) {
window.location.href = url;
}
//页面刷新
function refresh() {
window.location.href = window.location.href;
}
//判断布尔字符串
function parseBoolen(obj) {
if (obj == "True" || obj == "true" || obj == "TRUE")
return true;
else
return false;
}
//循环调用
function setIntervalOnce(callback, interval) {
callback();
setInterval(callback, interval);
}
//消息 注意引用common.css
function message(msg) {
if ($("body").length == 0) {
alert("缺少body");
return;
}
var messageDialog = $("#messageDialog");
if (messageDialog.length == 0) {
$("body").append('<div id="messageDialog" style="position: fixed;left: 50%;top: 3%;min-width: 200px;' +
'min-height: 50px;text-align: center; padding-top: 15px; background-color: darkcyan">' +
'<span id="messageContent"></span></div>');
messageDialog = $("#messageDialog");
}
var messageContent = $("#messageContent");
messageContent.html(msg);
messageDialog.show();
setTimeout(function () {
messageDialog.hide();
}, 3000);
}
//消息 注意引用common.css
function showMessage(msg) {
message(msg);
}
//遮罩 注意引用common.css
function showLoading() {
var loadingDialog = $("#loadingDialog");
if (loadingDialog.length == 0) {
$("body").append('<div id="loadingDialog"><div></div><img src="/common/loading.gif" /></div>');
loadingDialog = $("#loadingDialog");
}
loadingDialog.show();
}
function hideLoading() {
var loadingDialog = $("#loadingDialog");
if (loadingDialog.length > 0)
loadingDialog.hide();
}
//通知
function showNotification(msg) {
//判断兼容
if (window.Notification) {
//判断权限
if (window.Notification.permission == "granted") {
var notification = new Notification(msg);
setTimeout(function () {
notification.close();
}, 5000);
} else {
window.Notification.requestPermission();
}
} else
alert('你的浏览器不支持此消息提示功能,请使用chrome内核的浏览器!');
}
/*-------对象扩展------------*/
//对象扩展会导致jQuery选择器在选择不存在的对象时异常,引发matchExpr[type].exec is not a function
//toJsonString
//if (Object.prototype.toJsonString == undefined) {
// Object.prototype.toJsonString = function () {
// try {
// return JSON.stringify(this);
// }
// //这个去掉会引发Uncaught TypeError: Converting circular structure to JSON
// catch{ }
// }
//}
/*----------$.---------*/
//从timestamp中获取时间信息
$.fromStamp = function (stamp) {
var newDate = new Date();
newDate.setTime(stamp * 1000);
return newDate.getFullYear() + "-" + newDate.getMonth() + "-" + newDate.getDay() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
};
//输入框的值含空
$.valueEmpty = function () {
var args = arguments;
var result = false;
$(args).each(function (index, item) {
if (!result && $(item).val() == '')
result = true;
});
return result;
};
//两个输入框的值不一样
$.valueDiff = function (selector1, selector2) {
return $(selector1).val() != $(selector2).val();
};
//从文件导入html
$.loadWrite = function (url) {
$.ajax({
async: false,
type: "GET",
url: url,
success: function (html) {
document.writeln(html);
},
error: function (error) {
alert(error.statusText);
}
});
};
//消息提示
$.message = function (msg) {
showMessage(msg);
};
//载入遮罩
$.loading = function () {
showMessage("loading...");
showLoading();
};
//关闭遮罩
$.loadingHide = function () {
hideLoading();
};
//循环调用
$.loop = function (callback, intervalSeconds) {
setIntervalOnce(callback, intervalSeconds * 1000);
};
//get
$.httpGet = function (url, callback) {
$.loading();
$.ajax({
async: true,
type: "GET",
url: url,
success: function (data) {
$.loadingHide();
callback(data);
},
error: function (error) {
$.loadingHide();
$.message("ajax error: " + error.statusText);
}
});
};
//post any
$.postAny = function (api, data, callback, contentType, eCallback) {
//$.loading();
$.ajax({
async: true,
type: "POST",
url: api,
contentType: contentType,
data: data,
success: function (result) {
callback(result);
//$.loadingHide();
},
error: function (error) {
//$.loadingHide();
//$.message("ajax error: " + error.statusText);
alert("ajax error: " + error.statusText);
if (eCallback)
eCallback(error);
//$.alert(error.statusText);
//alert(error.statusText);
}
});
};
//post form
$.postForm = function (api, struct, callback) {
$.postAny(api, struct, callback, "application/x-www-form-urlencoded");
};
//post json
$.postJson = function (api, struct, callback, eCallback) {
$.postAny(api, JSON.stringify(struct), callback, "application/json");
};
//post text
$.postText = function (api, text, callback) {
//asp.net.core.api 不支持 [FromfBody]string,用 Request.GetBodyText() 代替
//$.postAny(api, text, callback, "text/html");
$.postAny(api, text, callback, "text/plain");
//$.postAny(api, text, callback, "text/richtext");
//$.postAny(api, text, callback, "text/xml");
//$.postAny(api, text, callback, "application/json");
};
//post null
$.postNull = function (api, callback) {
$.postForm(api, null, callback);
};
//上传文件
$.postFile = function (api, eleId, callback) {
$.loading();
var data = new FormData();
data.append("file", document.getElementById(eleId).files[0]);
$.ajax({
type: "POST",
url: api,
contentType: false, //tell jQuery not to set contentType
data: data,
processData: false, //tell jQuery not to process the data
success: function (data) {
callback(data);
$.loadingHide();
},
error: function (error) {
$.loadingHide();
$.message("ajax error: " + error.statusText);
}
});
};
//限制4M
$.postFileByBase64 = function (api, eleId, callback) {
$.loading();
var file = document.getElementById(eleId).files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var base64 = this.result.substring(this.result.indexOf(',') + 1);
var data = "name=" + file.name + "&" + "base64=" + base64;
$.postForm(api, data, callback);
}
};
//限制100M
$.postFileByJson = function (api, eleId, callback) {
$.loading();
var file = document.getElementById(eleId).files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var base64 = this.result.substring(this.result.indexOf(',') + 1);
$.postJson(api, { Name: file.name, base64: base64 }, callback);
}
};
//post
$.httpPost = $.postForm;
//delete
$.httpDelete = function (url, callback) {
$.loading();
$.ajax({
async: true,
type: "DELETE",
url: url,
success: function (data) {
$.loadingHide();
callback(data);
},
error: function (error) {
$.loadingHide();
$.message("ajax error: " + error.statusText);
}
});
};
$.delete = $.httpDelete;
var count = 1;
/*----------$.fn.-----------*/
$.fn.htmlAppend = function (html) {
$(this).html(count++ + '. ' + html + '<hr/>' + $(this).html());
}
$.fn.textAppend = function (text) {
$(this).text(count++ + '. ' + text + '<hr/>' + $(this).text());
}
$.fn.valInsert = function (val) {
$(this).val(val + $(this).val());
};
$.fn.valAppend = function (val) {
$(this).val($(this).val() + val);
};
var logCount = 0;
$.fn.log = function (val) {
$(this).valInsert(stringFormat("({0})[{1}]\r\n", ++logCount, new Date()) + val + "\r\n\r\n");
};
//获取/设置表单
$.fn.json = function (data) {
if (data == undefined) {
var json = {};
$(this).find("[name]").each(function (index, item) {
switch (item.type) {
case "checkbox":
json[item.name] = item.checked;
break;
default:
json[item.name] = item.value;
}
});
return json;
} else {
var json = {};
for (var key in data)
json[key.toLowerCase()] = data[key];
$(this).find("[name]").each(function (index, item) {
switch (item.type) {
case "checkbox":
item.checked = json[item.name.toLowerCase()];
break;
default:
item.value = json[item.name.toLowerCase()];
}
});
}
};
//输入框清空
$.fn.clearVal = function () {
$(this).val('');
};
//输入框只读
$.fn.readOnly = function () {
$(this).attr("disabled", "disabled");
};
//输入框可读写
$.fn.readWrite = function () {
$(this).removeAttr("disabled");
};
//判断是否隐藏
$.fn.isHidden = function () {
return $(this).is(":hidden");
}
//checkbox状态
$.fn.isChecked = function () {
return $(this).is(":checked");
};
//checkbox选中
$.fn.addChecked = function () {
$(this).prop("checked", true);
};
//checkbox取消选中
$.fn.removeChecked = function () {
$(this).prop("checked", false);
};
//只读
$.fn.readOnly = function () {
$(this).attr("readonly", "readonly");
};
//读写
$.fn.readWrite = function () {
$(this).removeAttr("readonly");
};
//禁用
$.fn.disable = function () {
$(this).addClass("disable");
};
//启用
$.fn.enable = function () {
$(this).removeClass("disable");
};
//获取整形
$.fn.int = function () {
var value = parseInt($(this).val());
if (isNaN(value))
return 0;
return value;
};
//checkbox选中开关
$.fn.toggleChecked = function () {
$(this).each(function () {
if ($(this).isChecked())
$(this).removeChecked()
else
$(this).addChecked();
});
};
//checkbox集里所有选中的checkbox的param
$.fn.checkedIds = function () {
var ids = "";
$(this).children("span").children("input[type=checkbox]").each(function () {
if (!$(this).isHidden() && $(this).isChecked())
ids += $(this).attr("param") + ',';
});
return ids;
};
$.fn.nextText = function () {
return $(this)[0].nextSibling.nodeValue.trim();
};
$.fn.preText = function () {
return $(this)[0].previousSibling.nodeValue.trim();
};
//输入内容
$.fn.inputs = function () {
var body = {
Source: location.href
};
var id = $(this).attr("form");
if (id == undefined || id.length == 0) {
alert("form error!");
throw new DOMException("form error!");
}
$("#" + id + " input[id]").each(function () {
if ($(this).preText().indexOf("*") != -1 && $(this).val().trim().length == 0) {
alert($(this).preText() + " can not be empty, 不可为空")
throw new DOMException($(this).preText() + " can not be empty, 不可为空");
}
body[$(this).attr("id")] = $(this).val().trim();
});
$("#" + id + " textarea[id]").each(function () {
if ($(this).preText().indexOf("*") != -1 && $(this).val().trim().length == 0) {
alert($(this).preText() + " can not be empty, 不可为空")
throw new DOMException($(this).preText() + " can not be empty, 不可为空");
}
body[$(this).attr("id")] = $(this).val().trim();
});
$("#" + id + " [type=radio][checked]").each(function () {
body[$(this).attr("name")] = $(this).nextText();
});
$("#" + id + " [type=checkbox]").each(function () {
body[$(this).attr("name")] = $(this).is(":checked");
});
$("#" + id + " [contenteditable]").each(function () {
body[$(this).attr("id")] = $(this).html().trim();
});
return body;
}
//select获取option
$.fn.selectFilt = function (type) {
$(this).children("option").hide();
if (type == -1)
$(this).children("option").show();
else {
$(this).children("option[type=" + type + "]").show();
$(this).val($(this).children("option[type=" + type + "]").val());
}
};
//select获取option
$.fn.option = function (value) {
if (value == undefined)
return $(this).children("option[value=" + $(this).val() + "]");
return $(this).children("option[value=" + value + "]");
};
//select获取option的文本
$.fn.optionText = function (value) {
return $(this).option(value).html();
};
//select同步select
$.fn.syncSelect = function (select) {
var option = $(this).option($(select).val());
if (option.length > 0)
$(this).val($(select).val());
};
//html匹配select的文本
$.fn.mateSelect = function (select) {
$(this).each(function () {
var text = $(select).optionText($(this).html());
if (text != undefined && text != '')
$(this).html(text);
});
};
/*--------$(document).ready-----------*/
$(document).ready(function () {
//值同步
$("[valuesync]").each(function () {
var item = $(this);
$("#" + item.attr("valuesync")).change(function () {
item.val($(this).val());
item.html($(this).val());
});
});
//点击事件同步
$("[clicksync]").click(function () {
$("#" + $(this).attr("clicksync")).click();
});
//图片上传预览
//示例 <img id="preview" /><input type="file" preview="preview" />
$('input[type=file][preview]').on('change', function () {
if (isImage($(this).val()))
$('#' + $(this).attr("preview")).attr('src', window.URL.createObjectURL(this.files[0]));
});
//格式化数字输入框
$(".number").each(function () {
if ($(this).attr("placeholder") == undefined)
$(this).attr("placeholder", "仅限数字")
$(this).keyup(function () {
var val = parseInt($(this).val(), 10);
if (isNaN(val))
val = ''
$(this).val(val);
})
});
//文件上传
$("[click=upload]").click(function () {
var api = $(this).attr("api");
var file = document.createElement("input");
file.type = "file";
$(file).change(function () {
var form = new FormData();
form.append("file", file.files[0]);
$.ajax({
url: api,
type: 'POST',
data: form,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (info) {
alert("error: " + info.status);
}
});
});
$(file).click();
});
//文本导入
$("[click=import]").click(function () {
var input = $($(this).attr("target"));
var file = document.createElement("input");
file.type = "file";
$(file).change(function () {
var reader = new FileReader();
reader.onload = function () {
input.val(reader.result);
};
reader.readAsText(file.files[0]);
});
$(file).click();
});
//访问api
$("[api]").click(function () {
$.postJson($(this).attr("api"), $(this).inputs(), function (result) {
alert(result.Message);
});
});
//跳转url
$("[url-locate]").click(function () {
window.location.href = $(this).attr("url-locate");
});
//新开启url
$("[url-open]").click(function () {
window.open($(this).attr("url-open"));
});
//访问url并刷新页面
$("[url-refresh]").click(function () {
$.get($(this).attr("url-refresh"), function () {
refresh();
});
});
//仅访问url
$("[url-null]").click(function () {
$.get($(this).attr("url-null"));
});
//WebSocketLog
$("#WebSocketLog").each(function () {
var textarea = $(this);
var url = textarea.attr("url");
var client = new WebSocket(url);
client.onopen = function () {
textarea.log("WebSocketLog open! " + url);
};
client.onclose = function () {
textarea.log("WebSocketLog close!");
};
client.onmessage = function (event) {
textarea.log(event.data);
};
});
//关闭按钮
$("button.close").click(function () {
$(this).parent().parent().hide();
});
//联动radio
$("input[type=radio],input[type=checkbox]").each(function () {
if ($(this).isChecked())
$("#" + $(this).attr("target")).show();
else
$("#" + $(this).attr("target")).hide();
});
//联动radio
$("input[type=radio],input[type=checkbox]").change(function () {
$("input[type=radio],input[type=checkbox]").each(function () {
if ($(this).isChecked())
$("#" + $(this).attr("target")).show();
else
$("#" + $(this).attr("target")).hide();
});
});
//同步email
$("input[type=email]").change(function () {
var value = $(this).val();
$("input[type=email]").each(function () {
$(this).val(value);
});
});
//同步用户名
$("input[type=name]").change(function () {
var value = $(this).val();
$("input[type=name]").each(function () {
$(this).val(value);
});
});
//富文本预览
$("[contentEditable]").on("input", function () {
$("[name=preview]").html($(this).html());
});
});
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/atalent/common-web.git
git@gitee.com:atalent/common-web.git
atalent
common-web
common-web
master

搜索帮助