JavaScript jQuery tips

JS常用信息:

 

  1. IE錯誤提示“缺少標識符、字符串或數字”,檢查JS文件中對象字面量是否最後包含逗號。比如
    var obj = {id: 1, name: 'test',};
     緊接'test'後那個逗號就會導致IE出錯。而FireFox正常。

  2. jQuery操作下拉菜單選定某個項目功能在IE中似乎無效。兼容辦法:
    document.getElementById( id ).selectedIndex = $('#' + id + " option[value='" + someval + "']").attr('index');
    
     
  3. jQuery判斷DOM是否存在:
    // 判斷DOM元素是否存在
    if ($('#id')[0] ) {
        do_fun();  // exists
    }
    if ($('#id').length > 0) {
        do_fun();
    }
    
     
  4. 錯誤的框架訪問:

    $(window.top.document).find('#topFrame p').text();	
    $(window.parent.document).find('#topFrame').remove();
     

    正確的框架訪問:

    $(window.parent.frames['left'].document).empty(); //刪除左框架“內容”
     

    在頂級窗口中 改變框架本身屬性,此時的框架是頂級窗口的一個DOM 對象

    $(window.parent.parent.document).find('#fs2').attr('cols', '155,*');
    $(window.top.document).find('#left').remove(); 
     

    以下是跨框架訪問操作DOM 元素 . frames  + id 的方式最兼容

    window.top.document.getElementById('left').id;
    window.top.frames[0].document.getElementById('SendFlag').id;
    window.top.frames['topFrame'].document.getElementById('SendFlag').id;
    window.top.frames['left'].document.getElementById('mli0').name;
    $(window.top.frames['left'].document).find('#mli0').attr('id');
    $(window.top.frames['topFrame'].document).find('p').text('cqple');
    $('p', window.top.frames['topFrame'].document).text('cqple');
     

     

  5. 子窗口操作父窗口

    // jquery
    $("#父窗口元素ID",window.parent.document)...就行了
    //js 版本
    window.parent.document.getElementById()
     

  6. jQuery 對象

    var el = $(selector);  // 取到的el變量爲jquery對象,el[0]則爲 selector對象
    var node = el.jquery ? el[0] : el; // el.jquery 返回真(其實是jquery版本號)說明el爲jquery對象
     
  7. jQuery ajax對提交值編碼規則
    如果是字符串類型不編碼,如果是對象則默認調用encodeURIComponent。所以如果$ajax data參數值是自己拼接的字符串那麼就需要手工編碼一次
    var pdata  = '&a=33' + '&b=' + encodeURIComponent('zz=3');
    // var pdata  = {a: 33, b: 'zz=3', c: 'z3&?aj=3', d: encodeURIComponent('z3&?aj=3')};
    
    $.ajax({
       type : "POST",
       url    : "some.php",
       data:  pdata
       success: function(msg){
         // do something
       }
    });
     






 

 

 

 

 

 

 

 

 

 

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