jquery或javascript日常使用记录

根据值动态选中select

$("#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动态选中

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的text

$(".pur_level").find("option:selected").text();

获取select被选中option的value

$("#att_hour option[selected='selected']").val();
$("#att_hour option[selected='selected']").val();
$("#att_hour").find("option:selected").val();

清除select选中

$("#me").find('option').removeAttr("selected");
$("#up_sex").find("option:selected").attr("selected", false);//和第一种选中集合会有bug

获取radio的选中值

<input type="radio" name="querytype" value="1">

$('input[name="querytype"]:checked').val();

移除radio选中

$("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; 
}); 

 

转载于:https://my.oschina.net/u/1760791/blog/646930

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值