根據值動態選中selectjavascript
$("#myDropDown option:text=" + myText +"").attr("selected", "selected"); //jquery1.9-
$("#me option[value='"+num+"']").prop('selected', true);//推薦使用,jquery1.9+,ie不支持prop
$('#me').val(num).prop('selected', true);//經測試沒有bug,推薦使用,jquery1.9+
原生javascript根據value動態選中css
function setSelectChecked(selectId, checkValue){ var select = document.getElementById(selectId); for(var i=0; i<select.options.length; i++){ if(select.options[i].value == checkValue){ select.options[i].selected = true; break; } } }
獲取select中被選中的option的texthtml
$(".pur_level").find("option:selected").text();
獲取select被選中option的valuejava
$("#att_hour option[selected='selected']").val(); $("#att_hour option[selected='selected']").val(); $("#att_hour").find("option:selected").val();
清除select選中jquery
$("#me").find('option').removeAttr("selected");
$("#up_sex").find("option:selected").attr("selected", false);//和第一種選中集合會有bug
獲取radio的選中值web
<input type="radio" name="querytype" value="1">ajax
$('input[name="querytype"]:checked').val();
移除radio選中spring
$("input[name=querytype]").removeAttr('checked');
檢測checkbox選中數組
<input type="checkbox" id="expireCheck" name="expireCheck" value="1">瀏覽器
$("#expireCheck").is(":checked")
checkbox設置選中和設置不選中
$("#expireCheck").attr("checked","true");//設置選中
$("#expireCheck").attr("checked",false);//設置不選中
對高版本的jquery,應該使用prop
$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);
根據數組值動態選中checkbox(注意數組中的每一項值需轉化爲string類型)
/** * set checkbox checked by values * @param selectId * @param checkBoxName * @param valuesArr */ setCheckedByValues:function(selectId,checkBoxName,valuesArr){ $("#"+selectId).find(':checkbox[name="'+checkBoxName+'"]').each(function(){ $(this).prop("checked", ($.inArray($(this).val(),valuesArr) != -1)); }); }
遍歷某個容器內的input
$("#up_cost input").each(function () { var cost = $(this).val(); var costTemp = cost.replace(/(^\s*)|(\s*$)/g,''); if(costTemp.length>0){ var level = $(this).parent().prev().attr('id'); var freestandObj = new freeStandards(cost,level); array.push(freestandObj); } });
遍歷某個容器內的checkbox
$("#checkboxContanier input[name='student']:checked").each(function () { if ($(this).val() !== null && $(this).val() !== "") { console.log($(this).val()); } });
使用window.location.href導出excel
var startTime = 12334444; var endTime = 44444444444444; var url = "/course/exportSche?startTime=" + startTime + "&endTime=" + endTime; window.location.href = url;
經過$.proxy綁定事件
this.$today = $("#today"); this.$today.off('click').on('click',$.proxy(this.todayClick,this)); Calendar.prototype.todayClick = function(event){ $(event.currentTarget).val();//獲取綁定元素的值 };
點擊頁面其餘地方關閉目標元素
//click other element close combo-select $(document).on("click",function(e){ if($(e.target).closest(".combo-select").length == 0){ $(".combo-dropdown").hide(); } })
jvascript獲取文件上傳的url
var url = null; if (window.createObjectURL != undefined) { url = window.createObjectURL(file); } else if (window.URL != undefined) { url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file); }
文件類型判斷:
ImgType: ["jpg", "png"] RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())
juery 爲子元素添加時間:
$(selector).delegate(childSelector,event,data,function)
jquery獲取同胞元素:
$("p").siblings(".selected")
jquery清空表單
$('#myform').trigger("reset");//只能清空普通文本 $("#myform").find(":input").not(":button,:submit,:reset") .val("").removeAttr("checked").removeAttr("selected");
或者
function clear_form_elements(ele) { $(ele).find(':input').each(function() { switch(this.type) { case 'password': case 'select-multiple': case 'select-one': case 'text': case 'textarea': $(this).val(''); break; case 'checkbox': case 'radio': this.checked = false; } }); }
或者封裝組件
$.fn.clearForm = function() { return this.each(function() { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'form') return $(':input',this).clearForm(); if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ''; else if (type == 'checkbox' || type == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }; //usage $('#flightsSearchForm').clearForm();
使用原生javascript清空元素
function clearForm(ele) { tags = ele.getElementsByTagName('input'); for(i = 0; i < tags.length; i++) { switch(tags[i].type) { case 'password': case 'text': tags[i].value = ''; break; case 'checkbox': case 'radio': tags[i].checked = false; break; } } tags = ele.getElementsByTagName('select'); for(i = 0; i < tags.length; i++) { if(tags[i].type == 'select-one') { tags[i].selectedIndex = 0; } else { for(j = 0; j < tags[i].options.length; j++) { tags[i].options[j].selected = false; } } } tags = ele.getElementsByTagName('textarea'); for(i = 0; i < tags.length; i++) { tags[i].value = ''; } } //usage:<input type="button" name="clear" value="Clear Form" onclick="clearForm(this.form);" >
jquery表單提交
// Using validation to check for the presence of an input $( "#form" ).submit(function( event ) { // If .required's value's length is zero if ( $( ".required" ).val().length === 0 ) { // Usually show some kind of error message here // Prevent the form from submitting event.preventDefault(); } else { // Run $.ajax() here } });
普通表單上傳文件
<form id="uploadForm"> <label for="excel-file">excel文件導入:</label> <input id="excel-file" type="file" name="filename" size="50"/> <button onclick="doUpload();">上傳</button> </form> <script> function doUpload() { var formData = new FormData($( "#uploadForm" )[0]); $.ajax({ url: '/importBrandSort' , type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { //alert(returndata); }, error: function (returndata) { //alert(returndata); } }); } </script> #後臺(spring mvc) @RequestParam("filename") MultipartFile file
jquery移出事件綁定:
對於新的jquery版本最好使用off而非unbind
$(this).off("mousemove");
獲取瀏覽器信息:
navigator.userAgent
禁止頁面嵌套框架:
if (window.top !== window.self) { window.top.location = window.location; }
禁止頁面跳出框架
if (window == top) { location.href = 'Where are you go!'; }
頁面session失效跳轉
$(function(){ $.ajaxSetup({ contentType : "application/x-www-form-urlencoded;charset=utf-8", complete : function(xhr, textStatus) { if (xhr.status == 401) { //Unauthorized ,back to index window.top.location = "../login"; return; } } }); });
刷新頁面
window.location.reload();
當前窗口的最頂層瀏覽器窗口
window.top
當前窗口最頂層瀏覽器窗口的文檔
window.top.document
jquery實現拖拽的基本思路
使div的position爲絕對定位absolute,而後控制其top與left值,須要監聽鼠標事件,主要用到mousedown, mousemove, mouseup。
在mousedown後,記錄mousedown時鼠標與須要移動的div的位置,而後取得二者之差,獲得在鼠標移動後,div的位置。即:
left = 當前鼠標位置.x - (鼠標點擊時的.x值 - div的初始位置x值)
top = 當前鼠標位置.y - (鼠標點擊時的.y值 - div的初始位置y值)
拖拽到指定區域:原理就是在mouseup時將拖拽元素appendTo在指定區域
$(document).ready(function(){ var move=false;//移動標記 var _x,_y;//鼠標離控件左上角的相對位置 $(".drag").mousedown(function(e){ move=true; _x=e.pageX-parseInt($(".drag").css("left")); _y=e.pageY-parseInt($(".drag").css("top")); }); $(document).mousemove(function(e){ if(move){ var x=e.pageX-_x;//控件左上角到屏幕左上角的相對位置 var y=e.pageY-_y; $(".drag").css({"top":y,"left":x}); } }).mouseup(function(){ move=false; });