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

檢查script object是否定義

$(function () {
    var result = "";              // 結果顯示位置
    var strObj = "1234";          // 字串變數
    var numObj = 5678;            // 數值變數
    var arrayObj = [1, 2, 4, 5];  // 陣列變數
    function functionObj() { }    // 函式變數
    // 字串物件型態
    result += 'typeof (strObj):' + typeof (strObj) + '<br/>';
    // 數值物件型態
    result += 'typeof (numObj):' + typeof (numObj) + '<br/>';
    // 陣列物件型態
    result += 'typeof (arrayObj):' + typeof (arrayObj) + '<br/>';
    // 函式物件類型
    result += 'typeof (functionObj):' + typeof (functionObj) + '<br/>';
    // 未定義物件類型
    result += 'typeof (nullObj):' + typeof (nullObj) + '<br/>';
    // jQuery物件類型
    result += 'typeof ($):' + typeof ($) + '<br/>';
    // 顯示結果
    $(".result").html(result);
});
結果:
typeof (strObj):string
typeof (numObj):number
typeof (arrayObj):object
typeof (functionObj):function
typeof (nullObj):undefined
typeof ($):function

javascript - execcommand:網頁文字編輯

execCommand(sCommand,bUserInterface,vValue) : 呼叫網頁的Command讓網頁選取位置產生變化,如: 文字處理{複製、貼上、剪下}、排版{對齊、編號、上下標}、變更字型與大小等等.


範例:
  • 前景色: document.execCommand('ForeColor',false,'#ff0000');
  • 背景色: document.execCommand('BackColor',false,'#ff0000');
  • 文字剪下: document.execCommand('Cut');
  • 文字複製: document.execCommand('Copy');
  • 文字貼上: document.execCommand('Paste');
  • 對齊左: document.execCommand('justifyleft');
  • 對齊中: document.execCommand('justifyleft');
  • 對齊右: document.execCommand('justifyleft');
  • 等寬對齊: document.execCommand('justifyFull');
  • 粗體字: document.execCommand('bold');
  • 斜體字: document.execCommand('italic');
  • 底線: document.execCommand('underline');
  • 刪除線: document.execCommand('strikethrough');
  • 變更字型: document.execCommand('fontname');
  • 變更大小: document.execCommand('fontsize');
  • 右縮: document.execCommand('indent');
  • 左縮: document.execCommand('outdent');
  • 編號: document.execCommand('orderedlist');
  • 標號: document.execCommand('unorderedlist');
  • 建立連結: document.execCommand('createlink');

javascript - 將網頁開啟編輯功能

下述語法直接將網頁變成編輯模式

if (document.body.contentEditable) {
    document.body.contentEditable = true;
}
else {
    document.designMode = "on";    
}

javascript - 用JavaScript產生iframe內容或變更網頁

產生iframe內容:

iframeobj.contentWindow.document.open();
iframeobj.contentWindow.document.write('<div> hello world!</div>');
iframeobj.contentWindow.document.close();

變更目前網頁內容:

var doc=document.open("text/html","replace");
doc.write('<div>hello world!</div>');
doc.close();

javascript - showmodaldialog與parent資料傳遞

// parent開啟showmodaldialog必須記得將window傳遞過去,以方便溝通。
var url='http://www.google.com';
var parm = "dialogWidth:300px;dialogHeight:300px;help:no;scroll:yes;"
    +"status:no;center:yes;resizable:yes;maximize:yes;minimize:yes;";
var result = window.showModalDialog(url, self, parm);
if(result!=null){
    // 有回傳值
    alert(result);
}

// child window可以利用傳來的window直接控制parent window
var parentDocument=window.dialogArguments.document;
// child window關閉前也可以將資料塞到returnValue回傳.
window.returnValue = "回傳資料"; // 回傳值
window.close();

javascript - 陣列 & Key/Value集合物件

陣列宣告方式:
var MyArray1=[];           // 比較喜歡這種
var MyArray2=new Array();  // 有時候會Error,還沒查出原因.
var MyArray3=new Array("A","B","C"); // 宣告&設定初始值
Key&Value集合物件:
var KeyValueCollection1={};  // 一般宣告
var KeyValueCollection2={    // 含初始值的定義方式
        "A1":"First Data",   // Key為字串建議用"或'包住
        "B2":{                         // Value可以為Key&Value Collection
            B21:{            // Key非"字串"型態也可,但命名有特殊符號就會js錯誤
                "Second's Child Data"  // Value可以為字串
            },
            B22:{
                1000                   // Value可以為數值
            }
        }
    };
使用心得:
一般情況下我比較喜歡用Key&Value集合物件來儲存的資料比較,如果儲存的資料格是一般變數格式(數值、字串、日期)的時候,很輕鬆可以轉成JSON Format與後端溝通。因此除非沒有Key值,不然我比較少使用Array的方式儲存資料。


javascript - function的apply/call

正常javascript呼叫function時,this變數是依賴function本身掛載的object,如:
buttonobj.click=function(){ alert(this.id);} // this=buttonobj
或者是指向符合存取條件之global object,如:
close(); // this=window
在這個this變數這麼玄的情況下,有些動態程式設計的便利性,需要去竄改function的this值時,javascript內建提供兩個隱藏method apply/call,來達成變更this的內容,而不需要在function內自行判斷.


利用apply/call變更function的this值

button1obj.click=showMyId;      // showMyId的this=button1obj
function showMyId(){
    alert(this.id);
}
button2obj.click=function(){    // showMyId的this=button2obj
    showMyId.apply(this);       // 自行指定showMyId function的this值
}
div.click=function(){           // showMyId的this=button2obj
    showMyId.call(button2obj);  // 自行指定showMyId function的this值
}
showMyId.apply({'id':'NotExistObjId'}); // showMyId的this為自訂array

apply與call的差異

apply(thisobj,argsArray);    // 用陣列方式傳入其他參數
call(thisobj,arg0,arg1...);  // 分別傳入其他參數

javascript - function的arguments/caller/callee

  • arguments - function的輸入參數array.
  • caller - 呼叫此function的function name,當null時表示最上層script執行的function.
  • callee - 目前正在執行的function name.

javascript - 定義function

基本function框架

  • 無輸入無輸出
function a() {
    alert('a');
}
a();    // call a function. show a
  • 有輸入無輸出
function b(input) {
    alert('b:'+input);
}
b("123");    // call b function. show b:123
  • 無輸入有輸出
function c() {
    alert('c');
    return "result";
}
var returnC = c();   // call c function. show c
  • 有輸入有輸出
function d(input) {
    alert('d:' + input);
    return input;
}
var returnD=d("input"); // call d function. show d:input
  • 階層式function定義,共用區域變數
function A1(input) {
    function B1() {
        return 'B1:'+input;
    }
    alert(B1());        // call B1 function
}
A1('input');            // call A1 function. show B1:input
try {
    B1();               // undefined exception
}
catch (e) { alert(e) };

  • 檢查Function是否存在,存在才執行:

if (typeof (customFunction) == 'function') {
    customFunction();
}

javascript - 定義變數

變數定義,一般可忽略型態,會依照使用轉換.

var iAmVaribles;
iAmVaribles=0;                        // 整數型態
iAmVaribles="string";                 // 字串型態
iAmVaribles=0.0;                      // 浮點數形態
iAmVaribles={};                       // 陣列
iAmVaribles=new Date();               // 日期物件
iAmVaribles={'A':'aaa','B':'bbb'};    // JSON格式
var iAmMethod=function(input){};      // 函式指標
iAmMethod("INPUT");                   // 執行涵式

取值轉換

var iAmVaribles="123.456";
alert(parserInt(iAmVaribles));        // show 123
alert(parserFloat(iAmVaribles));      // show 123.456

全域變數,直接使用就會變成全域變數

{
    iAmGlobalVaribles = 0;
    function iAmFunction() {
        alert(iAmGlobalVaribles);     // show 0
        iAmGlobalVaribles++;
    }
    iAmFunction();
    iAmGlobalVaribles++;
}
alert(iAmGlobalVaribles);             // show 2

區域變數

請用var來定義變數,有效範圍是該function內,如果function內還有其他function定義,也可以使用該變數.

function iAmFunctionA() {
    var iAmLocalVaribles = 0;// define local varibles
    iAmGlobalVaribles = 0;   // define global varibles
    alert(iAmLocalVaribles); // show 0
    iAmLocalVaribles++;
    iAmFunctionB();

    function iAmFunctionB() {
        alert(iAmLocalVaribles); // show 1
        iAmLocalVaribles++;
    }
}
iAmFunctionA();
alert(iAmGlobalVaribles);   // show 0
try {
    alert(iAmLocalVaribles);// undefined exception
}
catch (e) { alert(e); }

物件變數,直接指定該物件Propery/Method值即可使用.

var myObject = document;
myObject.newProperty = 0;
myObject.newMethod = function () {
    alert('newMethod called');
};
alert(myObject.newProperty); // show 0
myObject.newMethod();        // show newMethod called

javascript/jQuery 取消Button Click事件

$('#button_submit').click(function (e) {
    if ($('#txb_username').val() != ''
    && $('#txb_password').val()) {
        $('#button_submit').attr('disabled', true);
    }
    else {
        alert('Username/Password不允許為空值!');
        e.preventDefault()
    }
});


  • preventDefault是阻止預設行為的發生(如:onclick事件)
  • stopPropagation是會停止整個Event Tree往上繼續觸發
  • return false等於preventDefault與stopPropagation同時作用

不過在Google Chrome上面,return false不會有反應.


也可以使用下列語法直接取消事件泡:


window.event.returnValue = false;
window.event.cancelBubble = true;


javascript function的隱藏功能arguments/caller/callee

  • arguments - function的輸入參數array
  • caller - 呼叫此function的function name,當null時表示最上層script執行的function
  • callee - 目前正在執行的function name

javascript function的隱藏功能apply/call

正常javascript呼叫function時,this變數是依賴function本身掛載的object,如:
buttonobj.click=function(){ alert(this.id);} // this=buttonobj
或者是指向符合存取條件之global object,如:
close(); // this=window
在這個this變數這麼玄的情況下,有些動態程式設計的便利性,需要去竄改function的this值時,javascript內建提供兩個隱藏method apply/call,來達成變更this的內容,而不需要在function內自行判斷.

利用apply/call變更function的this值
button1obj.click=showMyId;   // showMyId的this=button1obj
function showMyId(){
    alert(this.id);
}
button2obj.click=function(){    // showMyId的this=button2obj
    showMyId.apply(this); //自行指定showMyId function的this值
}
div.click=function(){           // showMyId的this=button2obj
    showMyId.call(button2obj);  //自行指定showMyId function的this值
}
showMyId.apply({'id':'NotExistObjId'}); // showMyId的this為自訂array.

apply與call的差異
apply(thisobj,argsArray);    // 用陣列方式傳入其他參數
call(thisobj,arg0,arg1...);    // 分別傳入其他參數

透過Javascript取得目前Browser工作視窗大小

範例程式,打95折是留給Padding以及Margin預設值。
if (document.body.clientHeight)
{
var ll_object_h = document.body.clientHeight*0.95;
}
if(document.documentElement.clientHeight){
var ll_object_h=document.documentElement.clientHeight*0.95;
}
if (window.innerHeight)
{
var ll_object_h = window.innerHeight*0.95;
}
alert('可用高度:'+ll_object_h);

JavaScript - 檢查輸入範圍是否為0-9,a-z,A-Z,._

<script type="text/javascript" language="javascript" >
 function isRegisterUserName(s)
 {
  alert('isRegisterUserName');
  var textbox=window.document.getElementById(s);
  var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
  alert("s.text:"+s.value);
  if (!patrn.exec(s.value)) return false
   return true
 }
</script>

橫式廣告