2014年12月11日 星期四

ASP.NET 禁止重覆按下Button

參考資料1.重覆按下Button,造成重覆寫入問題??

參考資料2.How to avoid double click on submit button?

此篇參考上方資料,實作一次,並紀錄下來,請透過實作自行體驗。

程式碼如下

aspx檔
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript">
        var strpoint = '';
        function rec() {
            if (strpoint != '') {
                if (strpoint.length <= 2) {
                    strpoint = strpoint + '.';
                } else {
                    strpoint = '';
                };
            } else {
                strpoint = '.';
            };
            $('#<%=Label1.ClientID %>').html('訊息:請稍候' + strpoint);
            setTimeout("rec();", 1000);
        };
        function button1() {
            $('#<%=Button1.ClientID %>').attr('disabled', 'disabled');
            setTimeout(function () { rec(); }, 500);
            return true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="法1" UseSubmitBehavior="False"/>
        <asp:Button ID="Button2" runat="server" Text="法2" /><br/>
        <asp:Label ID="Label1" runat="server" />
    </div>
    </form>
</body>
</html>

apsx.vb檔
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            '方法1的第一種方法,此方法直接在onclick上寫入javascript語法
            'Button1.Attributes.Add("onclick", "this.disabled=true;")
            Button1.Attributes.Add("onclick", "button1();") '方法1的第二種方法

            '方法2 ClientScript.GetPostBackEventReference等於是加入__doPostBack方法
            Button2.Attributes.Add("onclick", "this.disabled=true;" & ClientScript.GetPostBackEventReference(Button2, "").ToString())
        End If
    End Sub

    Sub Loading()
        For i As Integer = 0 To 5000000
            Label1.Text = i.ToString()
        Next
    End Sub

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        '以下程式碼只是展示效果,沒有特別作用
        Loading()
    End Sub

    Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
        Loading()
    End Sub


以上如有錯誤請指正,謝謝

2014年12月7日 星期日

PhoneGap Android 跳出gap_poll訊息

參考資料1:Domain Whitelist Guide

問題敘述:
會出現,以下訊息
gap:["NetworkStatus","getConnectionInfo","NetworkStatus0",true]
...
gap_poll
最後會一直跳出gap_poll

解決方法:
Step 1.請開起您的Android專案底下的res\xml\cordova.xml,如下畫面
<?xml version="1.0" encoding="utf-8"?>
<cordova>
    <access origin="http://127.0.0.1*"/>
    <log level="DEBUG"/>
</cordova>

Step 2.請在<cordova>...</cordova>標籤之間加入白名單,如下
<?xml version="1.0" encoding="utf-8"?>
<cordova>
    <access origin="http://google.com" />
    <access origin="http://127.0.0.1*"/>
    <log level="DEBUG"/>
</cordova>

以上完畢


補充
2014/12/10
1.在html頁面中,如果有一個連結為<a href="https://www.google.com.tw" >Google</a>點擊此連結時,會自動開啟手機瀏覽器瀏覽器。如果不想自動開啟手機瀏覽器,請先找到res/xml/cordova.xml(會依版本不同而改變修改的位置)將<access origin="http://127.0.0.1*"/>改成<access origin="http://*"/>即可。


2014年11月13日 星期四

ASP.NET WebForm + JQuery RadioButtonList變更時,啟用DropDownList控制項

本篇直接使用JQuery來啟用或停用DropDownList,重點不使用ASP.NET的AJAX功能

前置作業:請先到JQuery官方網站下載jquery(我是使用v1.8.2)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="./Scripts/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //小於%=RBL_bhours.UniqueID %大於 是ASP的寫法,會將RBL_bhours控制項的唯一識別印出(類似ID)
            $('input[type="radio"][name="<%=RBL_bhours.UniqueID %>"]').change(function () {
                var bhours = this.value;
                //會先找到id="div1" 再 循序處理每個 select元素
                $('#div1 select').each(function () {
                    if (bhours == 'true') {
                        $(this).removeAttr('disabled'); //移除disabled等於啟用select元素
                    } else {
                        $(this).attr('disabled', 'disabled'); //加入disabled等於停用select元素
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:RadioButtonList ID="RBL_bhours" runat="server"
            RepeatDirection="Horizontal" RepeatLayout="Flow">
            <asp:ListItem Value="true">開啟</asp:ListItem>
            <asp:ListItem Value="false" Selected="True">關閉</asp:ListItem>
        </asp:RadioButtonList>
        &nbsp;&nbsp;
        <div id="div1">
            每月
            <asp:DropDownList ID="DDL_ts" runat="server" Width="45px" Enabled="false">
                <asp:ListItem>01</asp:ListItem>
                <asp:ListItem>02</asp:ListItem>
                <asp:ListItem>03</asp:ListItem>
            </asp:DropDownList>日
            到
            每月
            <asp:DropDownList ID="DDL_te" runat="server" Width="45px" Enabled="false">
                <asp:ListItem>01</asp:ListItem>
                <asp:ListItem>02</asp:ListItem>
                <asp:ListItem>03</asp:ListItem>
            </asp:DropDownList>日
        </div>
    </form>
</body>
</html>

2014年11月12日 星期三

javascript 應用篇




2017/06/16
取代字串中所有的blue為red。
var str = "Mr Blue has a blue house and a blue car".replace(/blue/g, "red");
取代字串中所有的blue為red,不區分大小寫。
var str = "Mr Blue has a blue house and a blue car".replace(/blue/gi, "red");
(參考:JavaScript String replace() Method)

2017/06/13
字串轉數值時,須注意字串前面是不是多了個0,當字串的數字是08、09時,parseInt會把它當作八進制處理,但是08、09都是不正確的八進制,我們可以在parseInt再加上第二個參數,例如:parseInt("08",10),告訴parseInt按照十進制處理,這樣就沒有問題了。
(參考:關于javascript中parseInt函數的一個所謂的bug)

2015/07/17
1. 全選checkbox。
<Script type="text/javascript">
function stcb(objcb){
  var checkboxs = document.getElementsByName('CB_Del'); 
  for(var x=0;x<checkboxs.length;x++){
    checkboxs[x].checked = objcb.checked;
  };
};
</Script>
<input type="checkbox" name="cb_total" id="cb1" onclick="stcb(this);" />
<label for="cb1" style=" font-size:10px;">全選</label>
<input type="checkbox" name="CB_Del" value="1">
<input type="checkbox" name="CB_Del" value="2">
<input type="checkbox" name="CB_Del" value="3">
<input type="checkbox" name="CB_Del" value="4">
<input type="checkbox" name="CB_Del" value="5">

2.變更form的action,並送出。
<Script type="text/javascript">
function but1_click(){
  document.f1.action='test.asp';
  document.f1.submit();
};
</Script>
....
<form name="f1" method="post">
<input name="but1" type="button" value="按鈕" onclick="but1_click();">
</form>
....

2015/05/20
1.變更link標籤的css檔
Step 1.首先再head標籤中引入css,id為cf1,如下:
<head>
...
<link rel="stylesheet" href="" id="cf1" />
...
</head>
Step 2.寫入下方的JavaScript,並呼叫它,即可修改CSS。
function change_css(){
  var css = document.getElementById("cf1");
  css.href = 'stylesheets/css1.css';
};

2.兩個日期時間相減,經過多少分鐘(取得經過多少毫秒轉分鐘)。
var d1=new Date("2015/05/19 19:18"); //假設登入時間
//getTime() 取得時間 (由 1970-01-01 00:00 到目前時間) 單位:(毫秒)
document.write('d1='+d1+' d1_num='+d1.getTime()+'<br/>');
var d2=new Date("2015/05/20 19:18"); //假設現在時間
document.write('d2='+d2+' d2_num='+d2.getTime()+'<br/>');
var num=d2.getTime()-d1.getTime(); //經過多少毫秒=目前時間(毫秒)-登入時間(毫秒)
document.write('num='+num+'<br/>');
//若要將毫秒數轉換為天數,請用 86,400,000 (1000 毫秒 x 60 秒 x 60 分鐘 x 24 小時) 除以毫秒數
document.write('毫秒 轉 分鐘='+(num/(1000*60))+'<br/>');

2015/03/30
1.按下按鈕出現請稍候訊息(請自行將ButtonFinish方法寫在Button的onclick事件中)
    <script type="text/javascript">
        var strpoint = '';
        function rec() {
            if (strpoint != '') {
                if (strpoint.length <= 2) {
                    strpoint = strpoint + '.';
                } else {
                    strpoint = '';
                };
            } else {
                strpoint = '.';
            };
            $('#span1').html('訊息:請稍候' + strpoint);
            setTimeout("rec();", 1000);
        };
        function ButtonFinish() {
            setTimeout(function () { rec(); }, 500);
        };
    </script>

2014/11/13
1.判斷手機是否為瀏覽器或手機瀏覽
    function checkerAgent() {
        var flag = false;
        if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
            flag = true;
        } else {
            //this is the browser
            flag = false;
        };
        if (flag == true) {
            document.location.href = './index1.html';
        } else {
            document.location.href = './index2.html';
        };
    };

2.倒數5秒鐘
    var s1=5;
    function rec() {
        if (s1 != 0) {
            $('#span1').text('倒數' + s1 + '秒'); //使用jquery設定span標籤
            setTimeout("rec();", 1000);
            s1 = s1 - 1;
        } else {
             $('#span1').text('時間到!!');
        };
    };

2014年11月10日 星期一

javascript 驗證表單格式


利用JQuery 取得欄位值,在透過javascript驗證檢查資料格式是否正確
function check_form(conphone, email) {
var str_message='';
var reg, strtel, strEmail;
strtel = ($('#' + conphone).val()).trim(); strEmail = ($('#' + email).val()).trim();
reg =/^[A-Z]\d{9}$/;  //身份證字號
reg = /(09[0-9]{2}-[0-9]{3}-[0-9]{3})|([0-9]{2}-[0-9]{6,8})$/;
if (reg.test(strtel) == false) {
str_message = f1(str_message, '聯絡電話格式錯誤,範例:0912-111-111或06-7211111');
};
reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/;
if (reg.test(strEmail) == false) {
str_message = f1(str_message, 'E-mail格式錯誤,範例:test@gmail.com');
};

if (str_message != '') {
alert(str_message);
return false;
};
return confirm("確定要送出嗎?");
};

function f1(str_mess, str_add) {
    if (str_mess == '') { str_mess = str_add + '\n'; } else { str_mess = str_mess + str_add + '\n'; };
    return str_mess;
};

2014年11月6日 星期四

ASP(Active Server Pages) 應用技巧篇


2014/11/07
1.取得host,並組成網址
<%
        '取得host,並檢查是否是https
if Request.ServerVariables("HTTPS")="on" then
str_url="https://" & Request.ServerVariables("HTTP_HOST")
else 'off
str_url="http://" & Request.ServerVariables("HTTP_HOST")
end if
Response.write(str_url)

        '========================
        '印出Request.ServerVariables所有資料
'for each x in Request.ServerVariables
'    response.write(x & "=" & Request.ServerVariables(x) & "<br>")
'next
%>

2014年10月17日 星期五

ASP 使用instr及Mid函數,從字串中擷取某一段字串


<%
dim str_temp1,SEHM_s,SEHM_e,str_SEHM,new_temp1

'假設str_temp1是我自己儲存在資料庫裡的資料,而我要擷取的是SEHM=10:00~12:00這段資料
str_temp1="TEMP=ABCD;SEHM=10:00~12:00;TEMP2=EFGH;"

'搜尋SEHM在字串中的起始位置
SEHM_s=instr(str_temp1,"SEHM")  '搜尋出來的位置是11

'instr(參數1 ,參數2 ,參數3)
'參數1:從哪一個位置,開始搜尋
'參數2: 此處指的是str_temp1
'參數3:要搜尋的字串
SEHM_e=instr(SEHM_s,str_temp1,";")+1  '搜尋出來的位置是27再加1等於28,加1是為了取得分號(;)

'Mid擷取字串的函數; Mid(str_temp1, 起始位置 ,(SEHM_e-SEHM_s))
str_SEHM=Mid(str_temp1,SEHM_s,(SEHM_e-SEHM_s))
Response.write("取得SEHM:" & str_SEHM & "<br/>")

new_SEHM="SEHM=09:00~10:00;" '假設是變更後的資料
'============================
'法1.直接取代原本的字串
new_temp1=Replace(str_temp1,str_SEHM,new_SEHM)
'============================
'法2.先將原本找到的字串資料替換成空白,在最後面插入新的資料
'new_temp1=Replace(str_temp1,str_SEHM,"")
'new_temp1=new_temp1 & new_SEHM
response.write(new_temp1 & "<br/>")
%>

2014年7月5日 星期六

ASP HtmlDecode 字串編碼轉換html

參考資料1:ASP Encode/Decode Functions

說明:當資料庫的資料儲存了換行的編碼,如:「 &#38;lt;br /&#38;gt;」(這是一個html換行的編碼)。那該如何轉換成html <br/>呢? 請看下列程式碼

程式碼
<%
Function HTMLDecode(sText)
    Dim I
    sText = Replace(sText, "&quot;", Chr(34))
    sText = Replace(sText, "&lt;"  , Chr(60)) '&lt 會被取代為 < 符號
    sText = Replace(sText, "&gt;"  , Chr(62)) '&gt 會被取代為 > 符號
    sText = Replace(sText, "&amp;" , Chr(38))
    sText = Replace(sText, "&nbsp;", Chr(32))
    For I = 1 to 255
        sText = Replace(sText, "&#" & I & ";", Chr(I)) '&#38 會被取代為 & 符號
    Next
    HTMLDecode = sText
End Function

Dim str_text
str_text="第一點&#38;lt;br /&#38;gt;第二點" '假設此變數為資料庫取出的資料
str_text=HTMLDecode(str_text) '呼叫第一次,此時回傳回來的值為「第一點&lt;br /&gt;第二點」
str_text=HTMLDecode(str_text) '呼叫第二次,此時回傳回來的值為「第一點<br />第二點」

Response.write str_text
%>

P.S 在傳統的ASP中沒有Server.HtmlDecode方法所以必須自行加入 HTMLDecode方法

2014年6月27日 星期五

ASP 使用JMail寄信

參考資料:http://www.ravs.ntct.edu.tw/know/show.asp?QUESTIONID=50

前置作業:
安裝JMail
1-1.先到Dimac Development下載 w3Jmail,下載前他會要您填寫資料,填寫完後即可下載,下載完後請先行安裝。
1-2.安裝完後,請到安裝的路徑(如 C:\Program Files (x86)\Dimac\w3JMail\ )底下複製 jmail.dll,請注意這裡將會有兩種狀況。狀況1:如果您的電腦是64bit請將檔案貼到C:\Windows\SysWOW64 ;狀況2:如果是32bit請將檔案貼到C:\Windows\System32。
1-3.請使用命令提示字元,下指令安裝JMail。
    (1)如果是32bit,請在命令提示字元執行regsvr32 jmail.dll
    (2)如果是64bit,請看下圖




程式碼:
Function JMailSend(MailTo,MailSubject,str_body,mailacc,mailpass,mailurl,mailcomp)
    Dim HTMLMailBody
    On Error Resume Next 
set jmail= server.CreateObject ("jmail.message")
jmail.Silent = true
jmail.Charset = "utf-8"

 '附加檔案
'filefullpath = Server.Mappath(".") & "\" & "test.doc"
'JMail.AddAttachment(filefullpath)

HTMLMailBody="<html><head><meta content=" & chr(34) & "text/html;" & chr(34) & " charset=" & chr(34) & "utf-8" & chr(34) & " http-equiv=" & chr(34) & "Content-Type" & chr(34) & "><title>test</title><style type=" & chr(34) & "text/css" & chr(34) & ">" & "</style></head><body>" & str_body &"</body></html>"

jmail.From = mailcomp '寄信人位址
jmail.FromName = "台灣" '寄件人名稱
jmail.ReplyTo = mailcomp '回信位址
jmail.Subject = MailSubject '信件title
jmail.AddRecipient MailTo '收件人地址
jmail.Body = "我們的郵件採用了HTML格式"
JMail.HTMLBody = HTMLMailBody


jmail.MailServerUserName = mailacc ' SMTP 登入帳號
jmail.MailServerPassWord = mailpass ' SMTP 登入密碼
jmail.Send(mailurl) '指定送信伺服器 SMTP
jmail.Close
set jmail = nothing
if Err.Number<>0 then '錯誤處理
'response.write Err.Description 
JMailSend=1
else 
 JMailSend=0
end if 


End Function

2014年6月26日 星期四

ASP.NET GridView 設定應用篇


20170904
1. GridView設定表格table、欄位td取消框線。
(1)GridView屬性BorderStyle設定為none
(2)GridView如果是自訂的TemplateField要取消欄位框線,可以設定ItemStyle的BorderStyle屬性為none

2. GridView套用bootstrap樣式。
    Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.Header Then
            e.Row.CssClass = "bg-primary"
            e.Row.Cells(0).CssClass = "col-xs-6 col-md-6"
            e.Row.Cells(1).CssClass = "col-xs-1 col-md-1"
            e.Row.Cells(2).CssClass = "col-xs-1 col-md-1"
            e.Row.Cells(3).CssClass = "col-xs-2 col-md-2"
            e.Row.Cells(4).CssClass = "col-xs-2 col-md-2"
        End If
    End Sub

20170619
1. GridView進入編輯模式時,設定欄位寬度。
Private Sub GridView3_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView3.RowDataBound
    If e.Row.RowState = (DataControlRowState.Edit Or DataControlRowState.Alternate) OrElse e.Row.RowState = DataControlRowState.Edit Then
        '按下編輯模式時,設定寬度
        e.Row.Cells(1).Style.Value = "width: 20%;"
    End If
    If e.Row.RowType = DataControlRowType.Header Then
        e.Row.CssClass = "bg-primary"
        e.Row.Cells(0).Style.Value = "width: 2%;"
        e.Row.Cells(1).Style.Value = "width: 10%;"
        e.Row.Cells(2).Style.Value = "width: 10%;"
    End If
End Sub



2. 設定GridView當沒有資料時,將框線設定為 0,也就是不顯示框線。
參考資料:emptydatarowstyle is not working

    Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.EmptyDataRow Then
            Dim bookingGridView As GridView = CType(sender, GridView)
            bookingGridView.Attributes.Add("border", "0") '框線為0
        End If
    End Sub


3.設定GridView上下顯示分頁功能、分頁對齊、分頁模式
2-1.如要在GridView的上下方同時顯示分頁功能,可設定PagerSettings.Position屬性,如下:
GridView1.PagerSettings.Position = PagerPosition.TopAndBottom
2-2.分頁對齊
GridView1.PagerStyle.HorizontalAlign = HorizontalAlign.Center
2-3.取得或設定在支援分頁的控制項中顯示頁面巡覽區控制項時所用的模式
.PagerSettings.Mode = PagerButtons.NumericFirstLast '上一頁、下一頁等多種分頁模式


4.當按下GridView中的編輯按鈕,如何在RowDataBound中攔截到使用者是編輯哪一列
    Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If e.Row.RowIndex = GridView1.EditIndex Then
                '在此處可以設定編輯模式中的TextBox1等控制項
            End If
        End If
    End Sub

2014年6月25日 星期三

asp.net web.config設定篇

201406
發生錯誤訊息:具有潛在危險 Request.Form 的值已從用戶端...偵測到
     當<pages validateRequest=ture...>(預設true)此時只要textbox有輸入html,送出資料後就會顯示具有潛在危險 Request.Form 的值已從用戶端偵測到;如果要關閉請先找到pages標籤並加上 validateRequest="false"或者在每個網頁的開頭<%@ Page ... %>加上ValidateRequest="false",此時送出後如果還是顯示一樣的錯誤訊息,請在system.web標籤之間加上<httpRuntime requestValidationMode="2.0"/> (此標籤只有.net 4才有)

2014年6月20日 星期五

JQuery UI accordion 設定標題、內容位置、cookie紀錄目前點擊的項目

參考1:asp.net+jquery accordion 按鈕點擊會收縮

說明:參考1的資料符合我要實作的需求,在此作了些補充及修改。另外下方的程式碼,少了另外一個登入的頁面,當使用者登入成功後,將會指定 $.cookie('index',0); ,轉到另外一個頁面(下方的程式碼)後accordion就會預設展開我們要展開的項目,因為有指定cookie的關係,當使用者重新整理時,accordion就會停留在目前點擊的項目。

程式碼如下
<head>
    <title></title>
    <link rel="stylesheet" href="themes/base/jquery.ui.all.css">
    <script type="text/javascript" src="Scripts/jquery.js"></script>
    <script src="Scripts/jquery.cookie.js"></script>
<script src="Scripts/jquery.ui.core.js"></script>
<script src="Scripts/jquery.ui.widget.js"></script>
    <script src="Scripts/jquery.ui.accordion.js"></script>
<script>
   $(function () {
//同時設定 active: false,collapsible: true 可讓項目呈現不摺疊(不展開)狀態
$('#accordion').accordion({
activate: function (event, ui) {
   //當click時觸發此處
if (($.cookie('index') == null) || ($.cookie('index')==undefined)) {
$.cookie('index', 0);
}else{
$.cookie('index', $('#accordion').accordion('option', 'active'));
};
},
active: parseInt($.cookie('saved_index'),10),
collapsible: true,
});
   });
</script>
    <style>
/**設定摺疊標題文字大小 padding: .5em .5em .5em .7em;*/
.ui-accordion .ui-accordion-header { display: block; font-size: 16px; }
/*設定摺疊標題為置**/
.ui-accordion .ui-accordion-icons {padding-left: 1.5em;}
/**.ui-accordion .ui-accordion-content 設定摺疊內容文字位置*/
.ui-accordion .ui-accordion-content {padding: 0.5em 0.5em; border-top: 0; overflow: auto; zoom: 1;}
    </style>
    <link type="text/css" rel="stylesheet" href="public_css.css"/>
</head>
<body>
    <form id="form1">
<div id="accordion">
<h4>項目1</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目2</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目3</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
</div>
    </form>
</body>
</html>

2014年6月10日 星期二

ASP.NET 使用DataSet+LINQ JOIN(關聯)資料表 (VB.NET語法)


參考資料1:聯結運算子 (LINQ to DataSet) 
參考資料2:使用 Joins 以 LINQ 合併資料 (Visual Basic)

說明:本篇主要是參考「參考資料1」,來進行實作。

前置作業:
1.請準備好兩個資料表,分別為 學生(Student)、班級(Class);
學生資料表欄位只需要三個欄位,分別為班級編號(class_id)、學號(stud_id)、姓名(stud_name)。
班級資料表欄位只需要兩個欄位,分別為班級編號(class_id)、班級名稱(class_name)。

2.請在Html中放入一個GridView,之後抓出來的資料丟到GridView

Code如下

Imports System
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Globalization

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Dim ds As DataSet = New DataSet
        ds.Locale = CultureInfo.InvariantCulture

        Dim connectionString As String = Nothing
        connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
        Using connection As SqlConnection = New SqlConnection(connectionString)

            Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
              "select st.class_id,st.stud_id,st.stud_name from Student as st where st.stud_id like '111%'", connection)

            connection.Open()
            adapter.Fill(ds, "student")

        End Using

        Using connection As SqlConnection = New SqlConnection(connectionString)

            Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
              "select cl.class_id,cl.class_name from class as cl", connection)

            connection.Open()
            adapter.Fill(ds, "class")

        End Using

        Dim stud_dt As DataTable = ds.Tables("student")
        Dim class_dt As DataTable = ds.Tables("class")

        Dim query = _
        From st In stud_dt.AsEnumerable() _
        Join cl In class_dt.AsEnumerable() _
        On st.Field(Of String)("class_id") Equals _
        cl.Field(Of String)("class_id") _
        Select New With _
        { _
            .class_id = st.Field(Of String)("class_id"), _
            .class_name = cl.Field(Of String)("class_name"), _
            .stud_id = st.Field(Of String)("stud_id"), _
            .stud_name = st.Field(Of String)("stud_name") _
        }

        '可印出資料
        'For Each strdata In query
        '    Response.Write(strdata.class_id & vbTab & _
        '        strdata.class_name & vbTab & _
        '        strdata.stud_id & vbTab & _
        '        strdata.stud_name)
        'Next

        GridView1.DataSource = query
        GridView1.DataBind()
    End If
End Sub

2014年6月9日 星期一

ASP.NET 兩個DataSet合併到另一個DataSet,並JOIN(關聯)DataSet中的資料(VB.NET語法)


參考資料1:瀏覽 DataRelation (ADO.NET)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim connectionString As String = Nothing

            Dim n1 As DataSet = Nothing
            n1 = New DataSet("newtable")

            Dim stud As DataSet = Nothing, cl As DataSet = Nothing

            connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
            Using connection As SqlConnection = New SqlConnection( _
   connectionString)

                Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
                  "select st.班級編號,st.學號,st.姓名 from 學生 as st where st.學號 like '111%'", connection)

                connection.Open()
                stud = New DataSet()
                adapter.Fill(stud, "student")

            End Using

            n1.Merge(stud.Tables(0))

            Using connection As SqlConnection = New SqlConnection( _
connectionString)

                Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
                  "select cl.班級編號,cl.班級名稱 from 班級 as cl", connection)

                connection.Open()
                cl = New DataSet()
                adapter.Fill(cl, "class")

            End Using

            n1.Merge(cl.Tables(0))

            '第四個參數 預設為True代表使用條件約束
            Dim StudClassRelation As DataRelation = n1.Relations.Add("StudClass", n1.Tables("student").Columns("班級編號"), n1.Tables("class").Columns("班級編號"), False)

            Dim studRow, classRow As DataRow

            For Each studRow In n1.Tables("student").Rows
                Response.Write("st.班級編號:" & studRow("班級編號").ToString() & " st.學號:" & studRow("學號").ToString())
                For Each classRow In studRow.GetChildRows(StudClassRelation)
                    Response.Write(" cl.班級編號:" & classRow("班級編號").ToString() & " cl.班級名稱:" & classRow("班級名稱").ToString() & "<br/>")
                Next
            Next
        End If
    End Sub

ASP.NET 兩個DataSet合併到另一個DataSet,並Select DataSet中的某一筆資料(VB.NET語法)

說明:先下SQL指令,分別Select兩個不同的資料庫-資料表,並將資料合併在同一個DataSet,且針對DataSet Select某一筆資料。

參考資料1:DataSet.Merge 方法 (DataTable)
參考資料2:DataTable.Select Method (String)


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            Dim connectionString As String = Nothing

            Dim n1 As DataSet = Nothing '將資料合併在這個DataSet
            n1 = New DataSet("newtable")
            Dim student1 As DataSet = Nothing, student2 As DataSet = Nothing

            connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
            Using connection As SqlConnection = New SqlConnection( _
   connectionString)

                Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
                  "select 班級,學號,姓名 from Student where 學號 like '400%'", connection)

                connection.Open()
                student1 = New DataSet()
                adapter.Fill(student1, "student1")

            End Using
            n1.Merge(student1.Tables(0))

            connectionString = "Server=127.0.0.1;Database=test2;uid=test;pwd=test"
            Using connection As SqlConnection = New SqlConnection( _
   connectionString)

                Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
                  "select 班級,學號,姓名 from Student where 學號 like '899%'", connection)

                connection.Open()
                student2 = New DataSet()
                adapter.Fill(student2, "student1") '這裡的student1如果更改成student2,合併後n1.Tables(0)只能看到student1的資料,而n1.Tables(1)才會看到student2的資料

            End Using
            n1.Merge(student2.Tables(0))

            GridView1.DataSource = n1.Tables(0)
            GridView1.DataBind()

            Dim expression As String
            expression = "stud_no = '89906141'" '要搜尋的條件
            Dim foundRows() As DataRow = Nothing

            foundRows = n1.Tables(0).Select(expression) '使用Select搜尋資料

            Dim i As Integer
            For i = 0 To foundRows.GetUpperBound(0)
                For j = 0 To foundRows(i).ItemArray.Count - 1
                    If j = foundRows(i).ItemArray.Count - 1 Then
                        Label1.Text = Label1.Text & foundRows(i)(j)
                    Else
                        Label1.Text = Label1.Text & foundRows(i)(j) & ","
                    End If
                Next
            Next
        End If
    End Sub

2014年6月6日 星期五

JQuery 應用篇

201706
1.取得table中的td欄位資料。
//jquery-1.11.3.js
$('#table1 > tbody > tr').each(function () {
//nth-child(3)取得第4個欄位資料
//$(this).find('td:nth-child(3)').text().trim()
 //如果要取得欄位中的TextBox就使用eq,取得第5個欄位的input
 //$(this).find('td:eq(4) input[type="text"]').val();
});
2.取得table中第一列之後的所有資料。
通常第一列會是表頭,如果要取得第一列之後的資料列,請使用下方的程式碼。
//:not排除、:first表格的第一列
//:not(:first)除了表格的第一行,其他的資料列都要
$('#table1 > tbody > tr:not(:first)').each(function () {
...
});

201705
1.檢查元素存不存在可以使用length來判斷,等於0不存在、>0代表存在。
if ($('#span_mess').length > 0) {
  //存在
}else{
  //不存在
};

201512
1.設定某個容器底下的checkbox全部勾選、全部取消(此例以table底下的checkbox為例)
//使用 jquery 版本v1.8.2
function CB1_checked(str_pid, int_dis) {
if (int_dis==1) {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', true); //全部勾選
} else {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', false); //全部取消
};
};

201411
1. 移除屬性(removeAttr)
$('#button1').removeAttr('onclick'); //移除button1 onclick

2. readonly
$('#id1').attr('readonly',true);

201406
1. HTML radio
1-1. 取得 radio 是否有選取項目
var str_iden=$('input[type="radio"][name="iden"]:checked').val();
if (str_iden==undefined){
    alert('您的身份尚未填寫');
    return false;  //在script標籤中,回傳false 會有終止程式執行的效果
};

1-2. radio 單選某個項目
$('input[type="radio"][name="iden"][value="1"]').attr("checked",true);

1-3. radio 停用與啟用
$('#input[type="radio"][name="iden"]').attr('disabled',true); //停用

1-4. 取得class是sall的元素,底下input type是radio,其值是1的項目(個人覺得如果是使用asp.net建議使用prop)。
$('[class="sall"] input[type="radio"][value="1"]').prop("checked", true);

2. HTML Checkbox
2-1. checkbox 是否有勾選此項目(適用於單一一個checkbox)
法1.
if ($('input[type="checkbox"][name="tt"]').attr('checked')){
   alert('您已勾選此項目');
}else{
   alert('您已取消此項目');
};

法2.(適用於JQuery 1.6以後的版本)
將 $('input[type="checkbox"][name="tt"]').attr('checked') 改成
$('input[type="checkbox"][name="tt"]').prop('checked')

2-2. 設定CheckBox勾選
$('input[type="checkbox"][name="tt"]').attr('checked',true); //可用在低版本的JQuery

補充:使用 attr('checked', true) 與 prop("checked", true)差別在於attr('checked', true)會在標籤裡增加checked的屬性,而 prop("checked", true)則不會在標籤裡增加checked屬性。

3. HTML Select
2-1. 取得下拉式選單選取的值及項目
$('select[name="s1"] option:selected').val();  //value
$('select[id="DDL1"] option:selected').text(); //項目

2-2. 設定下拉式選單項目為選取狀態(適用於JQuery低版本)
$('select[name="Area"] option[value="100"]').attr("selected",true);

2018/03/26 如果我的Html Select有設定class,例如我的class="hello",我也可以這樣子去設定Select要停留在哪一個選項。(使用的jquery版本是jquery-1.11.3)
$('.hello').val('0');

2014年4月2日 星期三

ASP.NET 使用Open Xml SDK 輸出Word檔

參考1:[Office]使用 OpenXML SDK 建立 Word 文件檔
參考2:[Office開發系列] 使用 OpenXML 將資料庫中的資料整合到 Word 文件中,且不假手 Office 物件模型
參考3:【雛型】Docx套版列印功能試作
參考4:How to: Insert a picture into a word processing document (Open XML SDK)

前置作業:
1.必須先下載安裝 Open XML SDK (我是使用 Open XML SDK 2.5 for Microsoft Office )

此篇純粹記錄程式碼
功能說明:取得現有的word檔,並在Word檔中的Table插入資料及圖片。

現有的Word檔(檔案名稱 testDoc.docx),格式如下圖:

程式產生出的Word檔,如下圖:


Code:

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports A = DocumentFormat.OpenXml.Drawing
Imports DW = DocumentFormat.OpenXml.Drawing.Wordprocessing
Imports PIC = DocumentFormat.OpenXml.Drawing.Pictures
'===============================================
Imports System.IO

Partial Class test_word
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

        End If
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim str_path As String = "C:\Users\SchoolDev\Desktop\test.docx"
        Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(str_path, WordprocessingDocumentType.Document)
            Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
            mainPart.Document = New Document()
            Dim body As Body = mainPart.Document.AppendChild(New Body())
            Dim par As Paragraph = body.AppendChild(New Paragraph())
            Dim run As Run = par.AppendChild(New Run())
            run.AppendChild(New Text("Hello,ASP.NET利用Open Xml Sdk產生Word檔"))
        End Using
    End Sub

    Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim fs As FileStream = ReadTemplateFile()
        Dim doc As WordprocessingDocument = WordprocessingDocument.Open(fs, True)

        Dim document As Document = doc.MainDocumentPart.Document
        Dim table As Table = document.Body.GetFirstChild(Of Table)()

        Dim lastRow As TableRow = table.GetFirstChild(Of TableRow)()
        For y1 As Integer = 0 To 3
            Dim newRow As TableRow = CreateItemRow(y1, 3, doc)
            table.InsertAfter(newRow, lastRow)
            lastRow = newRow
        Next

        doc.MainDocumentPart.Document.Save()
        doc.Close()
        fs.Close()
    End Sub
    Function ReadTemplateFile() As FileStream
        Dim newFileName As String = "C:\Users\SchoolDev\Desktop\" & "doc_" & DateTime.Now.ToString("yyyyMMddHHmmss") & ".docx"
        File.Copy(Server.MapPath("testDoc.docx"), newFileName)
        Return New FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
    End Function
    Function CreateItemRow(ByVal row_y As Integer, ByVal cell_x As Integer, ByVal word1 As WordprocessingDocument) As TableRow
        Dim tableRow1 As TableRow = New TableRow()
        For x1 As Integer = 0 To cell_x - 1
            Dim tableCell1 As TableCell = New TableCell()
            Dim par1 As Paragraph = New Paragraph()
            Dim run1 As Run = New Run()
            Dim text1 As Text = New Text()

            text1.Text = "name" & row_y & "-" & x1
            run1.Append(text1)

            Dim img1 As ImagePart = word1.MainDocumentPart.AddImagePart(ImagePartType.Png)
            Using imgstream As New FileStream(Server.MapPath("./images/Symbol.png"), FileMode.Open)
                img1.FeedData(imgstream)
            End Using
            'DW.Extent(){.Cx = 192000L, .Cy = 192000L} Cx調整寬度 Cy調整高度
            Dim relationshipId As String = word1.MainDocumentPart.GetIdOfPart(img1)
            Dim element = New Drawing( _
                              New DW.Inline( _
                              New DW.Extent() With {.Cx = 192000L, .Cy = 192000L}, _
                              New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
                              New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
                              New DW.NonVisualGraphicFrameDrawingProperties( _
                              New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
                                  ), _
                              New A.Graphic(New A.GraphicData( _
                                            New PIC.Picture( _
                                                New PIC.NonVisualPictureProperties( _
                                                    New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Picture.png"}, _
                                                    New PIC.NonVisualPictureDrawingProperties() _
                                                    ), _
                                                New PIC.BlipFill( _
                                                    New A.Blip( _
                                                        New A.BlipExtensionList( _
                                                            New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
                                                        ) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
                                                    New A.Stretch( _
                                                        New A.FillRectangle() _
                                                        ) _
                                                    ), _
                                                New PIC.ShapeProperties( _
                                                    New A.Transform2D( _
                                                        New A.Offset() With {.X = 0L, .Y = 0L}, _
                                                        New A.Extents() With {.Cx = 792000L, .Cy = 792000L}), _
                                                    New A.PresetGeometry( _
                                                        New A.AdjustValueList() _
                                                        ) With {.Preset = A.ShapeTypeValues.Rectangle} _
                                                    ) _
                                                ) _
                                            ) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _
                                        ) _
                                    ) With {.DistanceFromTop = 0UI, _
                                            .DistanceFromBottom = 0UI, _
                                            .DistanceFromLeft = 0UI, _
                                            .DistanceFromRight = 0UI} _
                                )
            run1.Append(element)

            par1.Append(run1)

            tableCell1.Append(par1)
            tableRow1.Append(tableCell1)
        Next

        Return tableRow1
    End Function

End Class

2014年3月23日 星期日

MS SQL指令應用篇

2022/12/06
查詢某個區段的資料,我們可以在條件上使用between,如下。
(欄位 between CONVERT(date,'2022-10-01') and CONVERT(date,'2022-10-31'))

2021/12/03
1. 字串1101203,拆出年、月、日,年轉西元年
Begin
Declare @StrTmp varchar(7);
Set @StrTmp='1101031';

Select (left(@StrTmp,3)+1911) as yy,CONVERT(int,substring(@StrTmp,4,2)) as mm,CONVERT(int,substring(@StrTmp,6,2)) as dd
End
2023/05/17 另一種方法就是將民國直接轉成數字,再加上19110000
CAST(str(CONVERT(int,left('1120101',7))+19110000) AS Date)

2019/07/02
Select Update指令如下
update fs set fs.Name=m.Name
From Table1 as fs left join Table2 as m on fs.ID=m.ID where m.Name is not null

Select Insert指令如下
Insert Table1 (t1,t2)
Select c1,c2 From Table2 where email='TEST@abc.com'

2019/03/28
通常會使用union去將很多張表合併成一張表,而union與union all的差別在於union all會將所有的資料都合併成一張表,所以得到的結果可能同一筆資料會出現兩筆以上的資料;如果使用union重複的資料則會顯示一筆。

2018/04/17
STATISTICS TIME
參考資料:[SQL SERVER] SET STATISTICS 語法執行時間分析與統計訊息
參考資料:SET STATISTICS TIME (Transact-SQL)
可以檢視自己的SQL指令,花了多少時間執行。
範例:
SET STATISTICS TIME ON;
GO

--SQL 語句--
Select  * from table1

GO

SET STATISTICS TIME OFF;
GO

2017/10/24
datalength函數:可以知道資料的長度,例如姓名中文3個字,在資料庫中的資料長度是6。
replicate(' ',4)函數:第一個參數是自己想要插入的字元,第二個參數是插入幾個字元。

2017/05/23
有一種狀況是某個欄位它不是主鍵,但它不能有重複的資料,這個時候可以透過UNIQUE來限制這個欄位的資料必須為唯一,就能避免重複的資料進入資料表時,指令如下:
ALTER TABLE 資料表名稱
ADD CONSTRAINT 自己給一個識別名稱 UNIQUE(欄位)
有一點要注意,欄位不能為NULL

2017/05/22
針對現有的資料表,運用指令方式加入外部索引鍵,以下是1對N的關係,每1張訂單會包含很多筆的訂單明細
ALTER TABLE test_order_detail
ADD
CONSTRAINT FK_test_order_detail_test_order
FOREIGN KEY (Order_no)
REFERENCES test_order(Order_no);
說明:
CONSTRAINT設定外部索引鍵的識別名稱,FK_test_order_detail_test_order是我自己自訂名稱。
FOREIGN KEY設定test_order_detail資料表的Order_no為外部索引鍵。
REFERENCES指定test_order資料表的Order_no為主鍵(主索引鍵)。

2015/05/11
利用CHARINDEX函數(搜尋字元位置),找出符合的資料;假設我們要針對某個資料表(名為table1),某ㄧ個欄位(名為status1,這個欄位會儲存A~D的英文代碼),找出符合A或C的代碼,如下:
Select *,CHARINDEX(status1,'AC') form table1 where CHARINDEX(status1,'AC')>0
說名:如果CHARINDEX函數有找到A或C,此函數就會回傳字元目前的位置。

2014/11/13
區分大小寫-在欄位後加上 Collate Chinese_Taiwan_Stroke_CS_AS(繁中區分大小寫)
select adm.userid,adm.password from s1 as adm
where adm.userid Collate Chinese_Taiwan_Stroke_CS_AS=@userid
and adm.password Collate Chinese_Taiwan_Stroke_CS_AS=@password

2014/10/29
使用CTE暫存資料,並執行刪除重複的資料,此方法適用於MS SQL 2005以上版本
說明:idno為學生學號,values為學生成績;由學生成績有高到低排序,並取最高的成績。
;WITH temp1 AS (
  select idno,values,ROW_NUMBER() OVER(partition by idno order by values desc) as aid from cv
)
DELETE FROM temp1
WHERE aid > 1;

補充:相同成績要相同排名ROW_NUMBER()改成RANK()

2014/09/03
--將年月日轉換為2014/09/03 10:00
select CONVERT(varchar(16),getdate(),120) as dt
--補充:如果要取到秒數,請將varchar(16)改為varchar(19);如果只想取得日期,請將varchar(16)改為varchar(10) 。
--取得日期時間的時間,例如:2014-09-03 08:02:24;執行下列指令會取得時間 08:02:24
select CONVERT(varchar(8),getdate(),108)
--補充:如果要取幾點幾分,請將varchar(8)改為varchar(5)。

2014/02/27
取得日期時間
參考資料:CAST 和 CONVERT (Transact-SQL)
--getdate取得現在時間;
select convert(varchar(10),getdate(),120) as str_date,convert(varchar(16),getdate(),120) as str_datetime

轉換int型態
select (CONVERT(int,'2014')-1911)-1 as s
轉換varchar型態
CONVERT(varchar, 欄位) as s

2014年3月19日 星期三

JavaScript 如何知道每個月的天數

參考資料:JavaScript實例判斷是否為正確日期格式

有時候我們會將使用者所輸入的日期作個比較,然後再來作進一步資料篩選的運用,但問題來了我怎麼知道每個月份的天數到底有多少天呢? 不管您是使用下拉式選單或輸入方塊(TextBox)讓使用者自行輸入,都會碰到這個問題。

以下是擷取參考資料裡的某段程式碼作修改,在此記錄下來

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Pragma" content="No-cache" />
<title>JavaScript日期應用</title>
</head>
<body>
<script>
var d = new Date();
document.write('今天日期是 ' + d.getFullYear()+ ' 年 ' + (d.getMonth()+1) + ' 月 ' + d.getDate() + ' 日 <br/>');
var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];//每個月的天數
for (var year=2000;year<=2030;year++){
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
iaMonthDays[1]=29; //有些年份的二月會是29天
document.write('<font color="Red">'+year+'年2月份天數為'+iaMonthDays[1]+'天</font><br/>');
}else{
   iaMonthDays[1]=28;
document.write('<font color="Blue">'+year+'年2月份天數為'+iaMonthDays[1]+'天</font><br/>');
};
}
</script>
</body>
</html>

2014年2月22日 星期六

JQuery 記錄使用者點擊li,重整後顯示點擊的li

只記錄使用者目前點擊的項目,不包含使用者點擊過哪些項目

參考資料:
jQuery教學-點選開啟下拉選單

前置作業:
使用JQuery-v1.6.4

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>記錄點擊li,重整後顯示點擊的li</title>
<script src="js/jquery.min.js" language="javascript"></script>
<script>
$(function(){
       //cookie不等於0
if( document.cookie.length!=0 ){
   var s_value=document.cookie.search('click_item=');//search字串搜尋,沒有找到為-1;
var e_value,str_CookTemp;
if( s_value!=-1 ){
s_value=s_value+('click_item='.length);
e_value=document.cookie.indexOf(';', s_value);
if( e_value==-1 ){
      e_value=document.cookie.length;
   }
str_CookTemp=document.cookie.slice(s_value,e_value);
//使用parents()可以取得DOM中的html元素;find搜索所有段落
var get_li=$('.menu ul:eq('+(str_CookTemp)+')').parents('li').find('a[href="#"]');
var str_title=get_li.html(); //取得title名稱
str_title=str_title.replace("►","▼");
get_li.html(str_title); //變更標題名稱
get_li.next().show();
}
}
$(".menu li a").click(function(){
var _this=$(this);
var on_li=$(this).closest('li'); //取得a上一層的li
var li_index=on_li.index(); //記錄li的index
document.cookie='click_item='+li_index+';'; //記錄點了哪一個li
if(_this.next("ul").length>0){
if(_this.next().is(":visible")){
//隱藏子選單並替換符號
_this.html(_this.html().replace("▼","►")).next().hide();
}else{
//開啟子選單並替換符號
_this.html(_this.html().replace("►","▼")).next().show();
}
//關閉連結
return false;
}
});

});
</script>
<style>
a{color:#333333; text-decoration:none; font-size:12px;}
a:hover{text-decoration:underline;}
ul{margin:0;padding:0;list-style-type: none;}
ul.submenu{display:none;}
ul.submenu{margin-left:25px;list-style-type:disc; color:#333333;}
</style>
</head>
<body>
<ul id="ulid" class="menu">
<li>
    <a href="#">►abc公司</a>
    <ul class="submenu">
        <li><a href="http://localhost/" target="_blank">部門1</a></li>
            <li><a href="http://localhost/" target="_blank">部門2</a></li>
        </ul>
    </li>
<li>
    <a href="#">►def公司</a>
    <ul class="submenu">
        <li><a href="http://localhost/" target="_blank">部門1</a></li>
            <li><a href="http://localhost/" target="_blank">部門2</a></li>
            <li><a href="http://localhost/" target="_blank">部門3</a></li>              
        </ul>
    </li>
    <li>
    <a href="#">►ghi公司</a>
    <ul class="submenu">
        <li><a href="http://localhost/" target="_blank">部門1</a></li>
            <li><a href="http://localhost/" target="_blank">部門2</a></li>
            <li><a href="http://localhost/" target="_blank">部門3</a></li>
            <li><a href="http://localhost/" target="_blank">部門4</a></li>      
        </ul>
    </li>  
</ul>
</body>
</html>

2014年2月18日 星期二

JQuery Mobile 應用篇

適用於JQuery Mobile-1.1.0

checkboxradio(Checkbox)設定
1.選擇input name=n1 值是100,設定為勾選,並刷新
$('input[name="n1"][value="100"]').prop('checked', true);
$('input[name="n1"]').checkboxradio(); //等同刷新-此方法是動態產生元件使用

2.選擇n2設定不啟用(可看到checkbox但無法點選)
$('input[name="n2"]').prop('disabled', true);
$('input[name="n2"]').checkboxradio(); //等同刷新-此方法是動態產生元件使用

3.建立事件
$('input[type="radio"][name="n2"]').bind( "change",function(){....});


selectmenu(Select下拉式選單)設定
1.選擇id=select1的選項值100設定為預設選項
$('#select1 option[value="100"]').prop('selected', true);
$('#select1' ).selectmenu(); //等同刷新-此方法是動態產生元件使用

2.選擇id=select2 設定為不啟用
$('#select2').prop('disabled', true);
$('#select1' ).selectmenu(); //等同刷新-此方法是動態產生元件使用

Button設定
1.按鈕顯示及隱藏
$('#Button1').closest('.ui-btn').show(); //按鈕顯示
$('#Button1').closest('.ui-btn').hide(); //按鈕隱藏

2.設定按鈕顯示文字
$("#Button1").prev('span').find('span.ui-btn-text').text("這是button1");

3.設定按鈕為不啟用(jquery.mobile-1.4.2可用)
$('#Button1').addClass('ui-state-disabled'); //不啟用
$('#Button1').removeClass('ui-state-disabled'); //移除ui-state-disabled 代表啟用

4.按鈕不啟用(jquery.mobile-1.4.4)
$('#Button1').button().button('disable');
P.S 如果是在ajax中執行可以寫成$('#Button1').button('disable');

備註
2015/01/13
1.假如在jquery mobile的pageinit事件中使用到jquery $post時,必須注意如果在javascript中有使用到$.mobile.changePage切換頁面,此時會在跑一次pageinit事件,大置上如下。
$(document).bind('pageinit', function (init_event) {
   //如果使用$.mobile.changePage切換頁面,會在跑一次pageinit
   $.post('a.aspx',{sd: str_comm},function(data, status){
   .....
   });
});

2014年1月13日 星期一

IIS6 設定寫入檔案

問題敘述:今日正在試著利用ASP.NET寫上傳檔案功能時,所遇到的問題,這可能之前也有遇過但當時並沒有記錄下來又或者筆記不知道被我埋沒到哪裡去了;而我寫的檔案上傳並不是使用ASP.NET中的FileUpload控制項來撰寫的,而是使用html的<input type=”File”/>撰寫的,再透過form的方式送到另外一個網頁做處理存檔的動作,不過我想只要想將檔案寫入(上傳)的Server端應該都必須做這樣的設定。

如果出現以下訊息,很有可能是IIS權限設定未設定成寫入所造成

伺服器應用程式無法使用
您嘗試在此 Web 伺服器上存取的 Web 應用程式目前無法使用。請按 Web 瀏覽器中的 [重新整理] 按鈕,再試一次。

系統管理員注意: Web 伺服器的應用程式事件記錄檔中的錯誤訊息詳細說明了這項特定要求失敗原因。請檢閱這個記錄項目,查看造成錯誤的原因為何。

解決方法:

Step 1. 開啟IIS6→在專案上按右鍵→點選:使用權限

Step 2. 點選:Users→勾選:寫入→確定

以上如有誤導請指正

2014年1月8日 星期三

PhoneGap使用開發IOS

本篇記錄如何使用PhoneGap套用在IOS的App專案上

前置作業:
1.請先在Mac電腦上安裝好IOS的開發環境
2.請到PhoneGap網站下載PhoneGap檔案(我是使用PhoneGap 2.9.1),並解壓縮

步驟:
Step 1.解壓縮完後,請切換到PhoneGap-2.9.1→lib→ios→bin資料夾底下


請先執行選擇:create檔案→右鍵→打開檔案的應用程式,點選:終端機.app

當點擊:終端機.app,會看到如下視窗:
請看到紅色框框,此處就是待會要下指令建立PhoneGap ios專案的指令
path_to_new_project:建立專案的路徑名稱,包含專案資料夾名稱
package_name:請自行看英文解釋,簡單講就是像android建立專案時要我們輸入的package
project_name:專案名稱

Step 2.PhoneGap-2.9.1→lib→ios→bin資料夾,按右鍵→選擇:「新增位於檔案夾位置終端機」並下指令,如下圖。

P.S如果指定的路徑有錯,會出現其它訊息

Step 3.建立成功後,請到剛剛建立專案的資料夾底下打開檔案(我的開發環境是xcode 5),點選左邊的config.xml,找到content標籤修改src屬性改成自己的網頁即可,最後請執行看看是否成功。



Apple Mac 設定技巧篇

本篇記錄有關Apple Mac電腦相關設定,因為自己對於Mac電腦不熟,所以自行記錄。

主要目錄如下:
1.滑鼠右鍵執行「新增位於檔案夾位置終端機」

內容:
1.新增位於檔案夾位置終端機
如果你對於在終端機下cd指令不熟,這個技巧還蠻方便的。
Step 1.系統偏好設定→鍵盤→快速鍵,選擇「服務」並勾選:新增位於檔案夾位置終端機,如圖下。

最後只要在你要的資料夾底下,按滑鼠右鍵→新增位於檔案夾位置終端機,就可以直接切換到資料夾底下的終端機



2014年1月2日 星期四

PhoneGap Android 縮放

參考資料1:zoom in phonegap for android

Step 1.在android程式碼先import WebSettings
import android.webkit.WebSettings;
import android.webkit.WebSettings.ZoomDensity;

Step 2. super.loadUrl之後加上

  WebSettings settings = appView.getSettings();
  settings.setBuiltInZoomControls(true);
  settings.setSupportZoom(true);
  settings.setDefaultZoom(ZoomDensity.MEDIUM);

android程式碼改完如下:
....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.htm");

WebSettings settings = appView.getSettings();
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDefaultZoom(ZoomDensity.MEDIUM);
}
....
Step 3.開啟htm檔,並修改meta標籤的viewport,改成如下:
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,user-scalable=1">

P.S注意,如果使用JQuery Mobile在html檔中的<div data-role="header" >或<div data-role="footer" >,不能有data-position="fixed"屬性值,否則無法縮放

PhoneGap Android 設定螢幕方向

參考資料1:phonegap -android横竖屏锁定
參考資料2:通過XML設置屏幕方向(android:screenOrientation)

如題,可能你會想說我想將App設定成,依照使用者手機旋轉的方向而定,那如何設定?
你只需要在AndroidManifest.xml檔中加入以下兩行設定,如下(紅色字體):
         <activity
            android:name="com.test"
            android:screenOrientation="sensor"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

如果你的android版本比較高(Android Level>=13),就必須再加上screenSize