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

jQuery 1.6之後的.prop() vs .attr()

有寫網頁的應該都不陌生jQuery啦,關於1.6之後突破性的prop,請參考以下二篇好文嚕

jQuery 1.6.1上場救援,不用改寫attr()囉
● .prop() vs .attr()

其實老早就改用jQuery1.6.2,甚至有些專案已經直上1.7或更新版本,但一直都沒發現主要是開發時都愛用Firefox+firebug,IE是偶爾想到測一下,沒想到一個舊專案被我發現用IE 7會有偶爾無法透過attr正確展示RadioButton勾選狀態的情況,好險改動方式極簡單,直接改用prop~收工!

舊寫法
$('#myRadioButton').attr('checked', false);

新寫法
$('#myRadioButton').prop('checked', false);

'JSON' 未經定義

Web專案中即使引入正確的jQuery檔案,在IE 6、7運行時,還是會出現 'JSON' 未經定義的狀況,例如使用JSON.stringify或 JSON.parse都有可能。

最簡單的方式是,去github下載一個名為json2.js檔案,接著將其include至會報錯的html即可。

本來的JSON寫法都不用變,引入即可!

How to select dropdown list item by text

在網頁上實作""修改現有資料""時,一般要讓Dropdownlist選中本來的值,大多有以下二種作法
1. 在後端組資料時就賦予哪一個是Selected="true"
2. 用jQuery讓符合指定value的選項被選中
    寫法為 $("#Dropdownlist的ID").val("指定的值");

在Telerik Grid中也是採用第二種作法
function Grid_onEdit(e) {
    var dataItem = e.dataItem;
    var mode = e.mode;
    var form = e.form;
    var priceTextBox = $(form).find("#Price");

    var customerDropDownList = $(form).find("#Customer");
    if (mode == "edit") {
        //Select the proper dropdown list item
        customerDropDownList.val(dataItem.CustomerID);
    }
}

但是,當Dropdownlist的Text和Value不同時,
customerDropDownList.val(dataItem.CustomerID); 寫法是無效且不合理的
因為dataItem.CustomerID取回的是Dropdownlist的Text,但jQuery的val是用來比對Value

解決的寫法如下
$("select option:contains(" + dataItem.CustomerID+ ")").attr('selected', true); 

解決IE 7無法動態append


IE 7下使用append或appendTo動態加入html element無效
google了很久發現大多數@解決辦法都是建議要有完整的結束標記,例如< div>開頭就要有< /div>結尾,即可避免append失敗的狀況。
但是,我實際在IE 9的F12開發者工具以IE 7模式測試還是沒反應,網頁也沒報錯。
後來才想到可能是DOM文件的不合理,因為我把div、input一堆有的沒的直接塞在table裡面,而不是塞tr、td這類的給table,
後來乖乖組合成合理的文件結構就好了

綜合以上,append的效果在Firefox、IE 8、IE 9都正常,在懷疑IE 7很爛前請先確認自己的Html合理 XD

使用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);
}

[jQuery].bind()與.live()之差異

最近看MSDN某教學影片使用到.bind()撰寫事件處理,想到最近撰寫MVC也是大量用到jQuery,對於常用到的.live()有點傻傻分不清楚,寫個小範例測試一下。

閱讀二者之使用說明,皆有( eventType, eventData, handler )模式可傳data,傳值的意義不在本文討論範圍,以下範例僅指定要處理的事件名稱(eventType)以及處理器(handler)


*範例效果—click DIV元素後會alert其text
情境1:.bind()寫在body
.bind()寫在body後
執行結果-DIV之click事件抓取text並alert

情境2:.bind()寫在body
.bind()寫在body前
執行結果-DIV之click事件沒反應

情境3 & 4:.live()寫在body or
.live()寫在body前
.live()寫在body後
執行結果-無論前後都可觸發click

依前述寥寥數圖可知.live()是對document所有elements作用,.bind()只對bind方法之前出現的element作用,此差異之說明文字引用官方網站如下
This method(此處只live方法) is a variation on the basic .bind() method for attaching event handlers to elements. When .bind() is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call. 

那麼這種差別有啥用處?重點在動態!!
有時候網頁元素是透過程式碼動態新增,並非一開始就設計好放在body等著被bind方法委派要使用的hanlder,此時live把元素通通抓起來的特性就派上用場,管你元素是何時生成,只要DIV被click一律都會alert(以前述範例而言)。


參考網址http://api.jquery.com/live/

[jQuery]jQuery的.add()方法

開發者不會滿足於透過jQuery取單一元素/值,多半需從龐大DOM中提取符合特定條件的元素,藉由.add()可取得更複雜的元素集合,且1.4版已經支援selector、element、html

■範例1:選取網頁內所有<div>與<span>元素
一般寫法
$('div,span')

使用.add()
$('div').add('span')

範例1還看不出.add()有別於多重selector的強大,接著來看範例2
■範例2:讓div與p元素擁有黃色背景色,且div元素還要帶紅色粗框 範例2的html
<!DOCTYPE html> <html> <head> <style> div { width:60px; height:60px; margin:10px; float:left; } p { clear:left; font-weight:bold; font-size:16px; color:blue; margin:0 10px; padding:2px; } </style> <script src="http://code.jquery.com/jquery-1.5.js"></script> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <p>Added this... (notice no border)</p> <script> $('div').css('border', '2px solid red') .add('p') .css('background', 'yellow'); </script> </body> </html>

範例2之Demo成果





思考一下Demo成果如何形成
1.先抓取所有div元素,指定border樣式為2px的紅色實線
2.再抓取所有p元素→此時元素集合包含所有div以及p元素!!!
3.針對此時的集合(所有div與p),指定background為黃色
4.依照這個思考順序,因此...div元素有紅粗框+黃背景;
透過.add()比較晚被抓取出來的p元素則只有黃背景!

瞧瞧~~這種效果就不是單靠selector搭配,運算子(範例1)可輕易達成,但.add()方法快速協助我們取得較複雜的集合以進行其他操作!


參考網址http://api.jquery.com/add/

[jQuery]取得id包含meta-characters之元素

初接觸jQuery者大多使用Selector時便深感jQuery簡潔之美,假設html如下 <div id="pets">我是個id為pets的div元素</div>
透過Selector取得id名稱為pets的元素,其jQuery如下 $('#pets')
不巧地...哪天接手如下的html,其中使用meta-characters替網頁元素取id(例如!"#$%&'()*+,./:;?@[\]^`{|}~) <div id="pets[dog]">我是個id為pets[dog]的div元素</div>
那麼Selector就需要透過跳脫字元\\撰寫 $('#pets\\[dog\\]')

參考網址http://api.jquery.com/category/selectors/