顯示具有 JavaScript 標籤的文章。 顯示所有文章
顯示具有 JavaScript 標籤的文章。 顯示所有文章

Convert an HTMLCollection to an Array

HTMLCollection is NOT an array !
The HTMLCollection interface represents a generic collection (array-like object) of elements (in document order).

So... If u want to use the method of Array like slice(), u need to convert HTMLCollection in advance.


Solution 
var convertedArray = Array.prototype.slice.call(YourHtmlCollection)
var convertedArray = [].slice.call(YourHtmlCollection);
var convertedArray = slice.call(YourHtmlCollection);

javascript single if

運用operator
condition && document.write("condition is true");

或使用if讓可讀較佳
if (condition) document.write("condition is true");

又或是用在變數
var myVariable = (condition) ? "condition is true" : "condition is false";

Short-Circuit Logic

Short-Circuit Logic短路邏輯或稱短路運算
在Java 與 JavaScript都是  紀錄一下 :-)

IE傳遞帶有中文的url會有亂碼


傳遞中文其實不常遇到,但這次的UI呈現上比較複雜,中文傳遞不可避免,
而且傳遞不是單單呈現在UI,而是做為某個複合key值的一部分,會出現在URL~
只好使用下列程式碼解決
var url = "有好幾個中文字的網址";
var sUrl = encodeURI(url);
實際轉址請用sUrl就不會有問題

以上問題,只有在IE會出現,Firefox和Chrome都不需要做額外處理!

C# / JS 無條件進位

用.NET寫Web就是用C#(或VB)和JavaScript,記錄一下數字的無條件進位寫法~

C#
Math.Ceiling(1.4) = 2 ;
JavaScript
Math.ceil(1.4) = 2 ;

使用jQuery傳遞Array

之前寫過一篇善用JavaScriptSerializer處理JSON資料,這次要傳遞的資料比較簡單,不是string就是List< string>,想當然爾會直覺地在前端用Array處理~方便咩。

JavaScript的Array長這樣
var myList = new Array();
最常見的用法就是把網頁上表單形式的排列資料,依所需取出以組合成陣列,
像是把table裡面每個的id值取出來
$('#myTable  tr').each(function () {
     var myId = $(this).attr('id');
     myList.push( myId  );
})
接著用$.post把資料往後送(我用MVC所以會有個Action接收)
$.post('myController/myAction', { json1: $.trim($('#textbox1').val()), json2: myList }, null, "json");

myAction如下
[HttpPost]
public JsonResult  myAction (string  json1, List< string>   json2)
{
     // do something
}
經過反覆檢驗,myList的確有值但json2總是null
解決辦法是traditional設為true,寫法有以下二種

● $.ajax設定traditional: true
$.ajax({
    type: "POST",
    url: 'myController/myAction',
    data: { json1: $.trim($('#textbox1').val()), json2: myList },
    null,
    dataType: "json",
    traditional: true
    // traditional 改為 ture .NET 才能成功接收陣列
});

● $.post傳值必須使用jQuery.param
var myObject = { json1: $.trim($('#textbox1').val()), json2: myList };
$.post('myController/myAction', $.param(myObject, true), null, "json");

參考資料
jQuery.param()
How can I post an array of string to ASP.NET MVC Controller without a form?

善用JavaScriptSerializer處理JSON資料

MVC開發常透過jQuery傳值,前陣子發現System.Web.Extensions提供一款好用的System.Web.Script.Serialization.JavaScriptSerializer,前端傳來的JSON資料只要下個簡單的JavaScriptSerializer,就能輕易將資料由JSON formate還原為想要的格式呢!

前幾天看到同事傳遞ListBox所有option到後端,方法是自組html string,後端接收到再反向重組成其他格式(例如SelectListItem),前後端都要大費不少行數去轉換資料~
後來piggy改採JavaScriptSerializer,輕輕鬆鬆就達到相同效果!寫法如下:


1.前端將ListBox內所有option組成JSON formate data
data以javascript的Array組合
function OK() {
var result = new Array();
$("#myListBox1 option").each(function () {
var item = {
Value: $(this).val(),
Text: $(this).text()
};
result.push(item);
});
var json = JSON.stringify(result);
$.ajax({
url: '@Url.Action("MyAction")',
type: 'POST',
data: { json: json }
});
}


2.後端接收資料以JavaScriptSerializer處理
public void MyAction(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
List< selectlistitem> myList = new List< selectlistitem>();
myList = jss.Deserialize< List< selectlistitem>>(json);
}

透過showModalDialog開啟新頁面,子視窗因PostBack再次開啟

嘖嘖...文章title像阿婆裹腳布一樣=..=|||
先以圖代文描述一下piggy上禮拜很開心搞定ICallBackEventHandler後遇到的小小絆腳石
用MooTool創造的側邊選單~還包含浮動效果0.<
威~~請不要責怪新開啟的定位視窗很醜T︿T
Demo階段piggy還不敢勞煩美編大人:P
前言說到的絆腳石XD

懂了吧?!雖然piggy小畫家功力爛爆了=..=|||

那要如何解決呢?差點要聽從ola兄建議,採用CallBack機制,但想想有夠抹爽~~不是很想為了這個搞大XDDDD
後來找到小撇步,透過修改子頁面(定位視窗)的< base target="_self" / >讓子頁面知道開啟時的方式,這樣就不會一直重複開新視窗嚕!那麼要安插在網頁那個位置呢,請看 <html>....略 <head runat="server">     <base target="_self"/>     <title>人孔編號</title > ....略 </head> ....略 </html>

不清楚怎麼使用JS開啟子視窗,或父子視窗如何傳值,請參考父子視窗傳值

強迫關閉視窗

很多場合需要強迫關閉視窗而不出現詢問視窗(如下圖),我加這個動作是為了防止user直接keyin完整網址去亂玩我的網站,廢話不多說直接說明下面的function如何使用
1.使用checkVersion()判斷IE版本
2.如果是IE6就使用A()把頁面強迫關掉
3.如果是IE7則使用B()把頁面強迫關掉


//IE 6
function A() {
    if (window.opener) {
    } else {
        window.opener = "null";
        window.close();   
    }
}

//IE 7 or 8
function B() {
    if (window.opener) {
    } else {
    window.open('', '_parent', '');
    window.close();
    }
}

function checkVersion() {
    for (i = 0; i < 10; i++) {
        for (z = 0; z < 10; z++) {
            if (navigator.appVersion.match("MSIE " + i + "." + z) != null) {              
                y = i;
            }
        }
    }

    if (y == '7' || y == '8' ) { B(); }
    else { A(); }
}

Bad Request(解決request中文傳值亂碼)

雖然撰寫程式時可盡量避免使用中文,但有些情況還是避免不了,就必須解決編碼的問題

可以使用的函數有Server.UrlDecode和Server.UrlEncode
如果是在前端(javascript)就要進行編碼工作,則是透過escape()以及unescape(),不過它們已經算是舊版的函示,建議還是使用decodeURIComponent()與encodeURIComponent()。

PS:piggy在開發時使用escape()在IE6、IE7都是沒問題的!

父子視窗傳值

承前面一篇的民國年份之月曆開發,在點選完日期後當然要將日期傳回至本來的父視窗,這時就面臨傳值的問題,以下為透過javascript的2個小方法。
(假設父視窗叫做parent.aspx,用來放置小月曆的子視窗叫做child.aspx)

1.方法一
開啟方式:window.open
傳值方式:opener

開啟方式ex:window.open('child.aspx','月曆選取器','width=300,height=300')
傳值方式ex:opener.form1.SelectDay.value = day;
(form1是父視窗的form名稱,SelectDay是父視窗裡面的一個text input,day就是子視窗小月曆提供的值)


2.方法二
開啟方式:window.showModalDialog
傳值方式:window.dialogArguments.form1.SelectDay.value = day;

開啟方式ex:window.showModalDialog('child.aspx',window,'dialogWidth:300;dialogHeight:300;')
傳值方式ex:window.dialogArguments.form1.SelectDay.value = day;
(form1是父視窗的form名稱,SelectDay是父視窗裡面的一個text input,day就是子視窗小月曆提供的值)

[心得]
★上述2種方法都可,要注意的是方法二要能讓父子視窗互動的話,一定要在showModalDialog的第2個參數填上window
★之所以後來採用方法二,是為了讓視窗永遠focus在child.aspx並顯示為最上層,這樣使用者在開啟child.aspx視窗後,就不會有忘記視窗已開啟而誤以為網頁無法傳值的問題!