隨筆

jquery形式追加option

$("<option></option>").val('nihaoma').text('wohenhao').appendTo("select[name='coupons_type']");

//定義一個全局變量來控制優惠劵ajax請求緩存
	var data_cache = {coupons:{is_request:'0',data:''},daijinjuan:{is_request:'0',data:''}};	//定義一個對象用來緩存請求的數據
	//定義一個將緩存數據填充至select標籤選項卡中的函數,result:json數據,coupons_name待追加的對象
	var json_append_option = function (result,coupons_name){
		if(result){
			coupons_name.css('display','inline');
    		$.each(result, function (i, item) {
    	  	$("<option></option>").val(item.id).text(item.coupons_name).appendTo(coupons_name);
    	  });
		}else{
			coupons_name.empty();
			$("<option></option>").val('').text('請選擇').appendTo(coupons_name);
			coupons_name.css('display','none');
		}
	}
	
	//優惠劵方式更改時的方法
    $("select[name='coupons_type']").change(function(){
    	var url = "/wechat/wemember/expense?inajax=1&aid=<{$view->aid}>&id=<{$view->id}>";
    	var coupons_name = $("select[name='coupons_name']");
    	
    	//緩存控制判斷
    	switch($(this).val()){
	        case "優惠劵":
	        	var type = '1';
	        	if(data_cache.coupons.is_request == '1'){
	        		var is_cache = '1';
	        		var cache_data = data_cache.coupons.data;
	        	}else{
	        		var is_cache = '0';
	        	}
	            break;
	        case "代金劵":
	        	var type = '2';
	        	if(data_cache.coupons.is_request == '1'){
	        		var is_cache = '1';
	        		var cache_data = data_cache.daijinjuan.data;
	        	}else{
	        		var is_cache = '0';
	        	}
	            break;
		}
    	//判斷當前的請求數據是否已經緩存
    	if(is_cache == '0'){
	    	//ajaxa數據請求
	    	$.getJSON(url, { coupons_property: $(this).val() }, function (result) {
	    		//緩存當前請求的數據
	    		switch(type){
			        case "1":
			        	data_cache.coupons.is_request = '1';
			        	data_cache.coupons.data = result.data.data;
			            break;
			        case "2":
			        	data_cache.daijinjuan.is_request = '1';
			        	data_cache.daijinjuan.data = result.data.data;
			            break;
				}
	    		//將請求數據填充至select選項中
	    		json_append_option(result.data.data,coupons_name);
	    	});
    	}else{
    		//將緩存數據填充至select選項中
    		json_append_option(cache_data,coupons_name);
    	}
    });


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章