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

星期日, 6月 11, 2017

[jQuery] 特殊字元跳脫的錯誤解決方法: Syntax error, unrecognized expression: a[href*=#]:not([href=#])

今天在移轉舊專案程式碼,遇到jquery一些錯誤,
查了一下原來是用的2.x版有特殊字元要跳脫的問題,記錄一下。
Syntax error, unrecognized expression:

your selector is not valid. # is a special char and needs to be escaped like 'a[href*=\\#]:not([href=\\#])'

https://github.com/jquery/jquery/issues/2885

星期三, 6月 17, 2015

星期一, 4月 20, 2015

[jQuery API] 如何讓元素透過tabindex來達到Focus效果

今天在實作一個下拉選單顯示與隱藏的效果(透過點擊一個按鈕)
當下拉選單出現時,設定呼叫focus(),反之在失去Focus時,會自動hide。

加入tabindex屬性,讓元素(div or ul)支援focus方法

//再focus執行前,加入tabindex屬性
  $dropdownMenu.attr('tabindex',-1).fadeIn().focus();

偵測被Focus的元素的方法

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

去除瀏覽器的tabindex外框

當你讓選單focus的時候,會發現外框出現的色框


可以透過以下css,讓border消失

:focus { 
    outline: none; 
}

參考


星期二, 2月 03, 2015

[jQuery API] IE8 隱藏column後表格寬度異常解決方法

昨天遇到ie8在表格的column隱藏時,表格的寬度未自動變動的問題。
慘況如下圖記念擷圖


找到這個作者的解法,透過變動display的屬性成inline-talbe,再透過setTimeout再把dispaly重設,表格的寬度就會正常了。


星期四, 12月 18, 2014

[jQuery API] 小心元素undefined的操作,而引起的getAttribute

當操作使用jquery selector操作未定義的物件所引起的getAttribute的錯誤的小地雷


Uncaught TypeError: Cannot read property 'getAttribute' of undefined
var iframe = $("#videoIntro")[0];
       if (typeof(iframe) != "undefined") {
           var player = $f(iframe);
}

星期一, 11月 17, 2014

[jQuery API] JSON SyntaxError: Unexpected token s

今天call同事的api,發現http status都是200正確,但都跑到$.ajax的error handler

17 Nov 2014 17:39:07,698 [DEBUG] [frmDeviceMgmt] jqXHR.responsetext: undefined log4javascript.min.js:155
17 Nov 2014 17:39:07,700 [DEBUG] [frmDeviceMgmt] textStatus: parsererror log4javascript.min.js:155
17 Nov 2014 17:39:07,700 [DEBUG] [frmDeviceMgmt] errorThrown: SyntaxError: Unexpected token s

查了一下原來是回傳的JSON格式是驗證錯誤的關係,踩雷共勉之:D

星期六, 11月 01, 2014

[AngularJS] 使用jquery來呼叫Angular scope 方法與更新變數

想在舊的jQuery專案內呼叫Angular的方法與變數,可以在jquery中使用以下方法取得scope

var ngScope = angular.element(document.getElementById('元素ID')).scope();

ngScope即可以操作原本在ng內的方法與變數了,在透過jquery更新完變數後,記得要呼叫$apply來告知Angular裡面的變數的值已改變了!!

參考以下完整範例:



星期三, 11月 27, 2013

[jQuery API] 如何使用$ajax進行 multiple-part/form-data 傳輸

這幾天整合summernote編輯器的上傳,
順便記錄一下如何使用jquery $ajax進行multiple-part的上傳方式
var formdata = new FormData();
//指定欄位的name與binary string
    formdata.append("fileToUpload", file);
    $.ajax({
        data: formdata,
        type: "POST",
        url: "your_api/upload_imgur/" + uid,
        // cache: false,
        contentType: false,
        // dataType: "json",//用這個叫api會404
        processData: false,
        success: function(rJSON) {
            $.console("send file callback:");
}
});
參考https://github.com/HackerWins/summernote/issues/72

星期二, 10月 01, 2013

[jQuery] beforeunload 踩到雷

由於在處理某個議題了,加入監聽beforeunload事件,目前由於有透過window.location.href進行檔案下載的動作,好死不死在chrome,也會因為這個指令而跑到beforeunload的事件。
google找到了對岸的實驗結果(http://www.w3help.org/zh-cn/causes/BX2047),如下表,不過應該在這瀏覽器會更新的時代只能僅供參考,要自已實驗XD
执行结果汇总入表:
IEFirefoxChrome SafariOpera
关闭当前浏览器窗口事件被触发事件被触发事件被触发不支持该事件
导航到另一个进入一个新的地址或选择一个喜欢的位置事件被触发事件被触发事件被触发不支持该事件
单击后退,前进,刷新,或主页按钮事件被触发事件被触发事件被触发不支持该事件
点击一个链接到新页面事件被触发事件被触发事件被触发不支持该事件
调用 anchor.click方法事件被触发不支持此方法1不支持此方法1不支持该事件
调用 document.write方法事件被触发事件被触发事件未触发不支持该事件
调用 document.open方法事件被触发事件被触发事件未触发不支持该事件
调用 document.close方法事件未触发事件未触发事件未触发不支持该事件
调用 window.open方法,窗口名称设置值为 _self事件被触发事件被触发事件被触发不支持该事件
调用 window.navigate事件被触发不支持此方法2不支持此方法2不支持该事件
调用 NavigateAndFind方法事件被触发不支持此方法3不支持此方法3不支持此方法3
调用 location.replace 方法事件被触发事件被触发事件被触发不支持该事件
调用 location.reload 方法事件被触发事件被触发事件被触发不支持该事件
指定一个 location.href 属性的新值事件被触发事件被触发事件被触发不支持该事件
使用 submit 按键提交表单事件被触发事件被触发事件被触发不支持该事件
调用 form.submit 方法事件被触发事件被触发事件被触发不支持该事件
调用 javascipt: 伪协议事件被触发事件未触发事件未触发不支持该事件
调用 mailto: 伪协议事件未触发事件未触发事件被触发不支持该事件
调用自定义伪协议事件被触发事件被触发事件被触发不支持该事件

星期三, 9月 18, 2013

[jQuery] 如何控制textbox按enter後往下一個textbox移動

在提供使用者使用表單填寫資料時,如果欄位爆多的時候,
通常使用者會習慣打完資料按enter鍵後能自動往下一個欄位移動。
如果你有這個需求可以參考以下這個範例。
http://jquerybyexample.blogspot.com/2011/05/how-to-set-focus-on-next-textbox-on.html

實作方法透過偵測現在有多少input textbox,再透過遞增textbox index方式即可簡單做到
$('input:text')[nextIndex].focus();

把它改成外掛會更好使用。


星期日, 9月 01, 2013

[jQuery] IE8踩雷: 使用$('element')建立元素未加入結尾

最近寫了一個dropbox like breadcrumbs的外掛,
結果在IE8測試下有個地方沒反應,
查了一下是建立元素的時候沒有結尾

//會爆掉!!
//  var $anchor = $("<a data-id='" + nodeData.id + "'>");
  var $anchor = $("<a data-id='" + nodeData.id + "'></a>");

星期四, 5月 09, 2013

[jQuery API] removeData 一直都拿不掉資料 WTF

今天發生一很怪的bug,想要用removeData移除先前暫存的資料一直移不掉(某些特別的key:user_jmeter-slave1-user1),如果像是簡單一點的ken,jack倒是沒問題。
想說是不是這個key,對$data方法會有bug發生。

結果寫了測試的方法也沒問題!!,範例如下

http://jsfiddle.net/e92s6/2/

但是在 瀏覽器下的console執行js code也不行。

最後發現jquery官方找到了另一條思路的解法(http://jsfiddle.net/rwaldron/AvqeW/9/),
就是再把資料設成null就好了

範例如下:
//清掉資料
$.data("your_key",null)

//判斷資料還存不存在,如果沒存過第一次是會找到undefined!!
var queryUserData = $.data("your_key",null)
if(typeof (queryUserData) == "undefined" || queryUserData == null){
      //做你要幹的事
  //.....
}



星期三, 4月 24, 2013

[jQuery plugin] 實作Shift + Click多選行為

如果要模擬window shift鍵多選的行為,可以參考以下這篇文章。
Snippet: Shift + Click List Items with jQuery
主要的邏輯是記錄最後一個選擇的項目
$parentNode.delegate("li","click",function(event){
    
    var $currLI = $(this);
   
    if($currLI.hasClass("select_this")){
     
     //unselected
     $.console("[UserList.render] delegate:unselected user");
     
     if(event.shiftKey){
      //just unselected
      $currLI.removeClass("select_this");
     }else{
      //re-locate last selected/unselected
      $currLI.removeClass("select_this");
      $currLI.addClass("last_selected");
      
      $lastSelected.removeClass("last_selected");
      
      //change last selected
      $lastSelected = $currLI;
     }
    }else{
     
     //selected 
     $.console("[UserList.render] delegate:selected user");
    
     //
     // SHIFT + CLICK
     //
     
     var $shiftSelected = [];//record seleted items by shfit key
     if(event.shiftKey){
      
      //shift + click logic 
      if($lastSelected.length > 0){//first click
       
       if($lastSelected == $currLI){
        $.console("[UserList.render] same selection");
        
        return false;
        
       }else{
        
        //detect foward or back
        direction = $currLI.nextAll(".last_selected").length > 0 ? "forward" : "back";
        $.console("[UserList.render] last_selected count:" + $currLI.nextAll(".last_selected").length);
        $.console("[UserList.render] direction:" + direction);
        
        if(direction == "forward"){
         $shiftSelected = $currLI.nextUntil($lastSelected);
        }else{
         //back
         $shiftSelected = $lastSelected.nextUntil($currLI);
        }
        
//        $.console("$shiftSelected:" + $shiftSelected.length);
        $LICollection.removeClass("select_this");//reset pre selected
        
        //final selected items
        $shiftSelected.addClass("select_this");//highlight shift selected
        $lastSelected.addClass("select_this");//highlight last selected
                 $currLI.addClass("select_this");//highlight current selected
                 
       }
       
      }else{
       
       $lastSelected = $currLI;
       $currLI.addClass("select_this last_selected");
      }
      
     }else{
      
      //record last selected
      $lastSelected = $currLI;
      $currLI.addClass("select_this last_selected");
  
     }
     
    }
    
    //for debug
//    $.console("lastselected username:" + $lastSelected.find(".usr_name").html());
    
    if(userlist.selecteEventHandler && typeof(userlist.selecteEventHandler) === "function"){
     userlist.selecteEventHandler($currLI,userlist.getSelectedItems());
    }
   });

星期五, 4月 19, 2013

[jQuery API] append加上fadeIn的效果

今天要遇到想要在append新元素時,加入fadein的效果。
筆記一下..
//userElem為html tag
$(userElem).hide().appendTo($parentNode).fadeIn(1000);

星期二, 3月 19, 2013

[jQuery] 如何觸發超連結click動作

今天在模擬使用File API下載檔案,需要一個觸發超連結引發下載的動作,筆記一下。
//dom api
document.getElementById('dllink').click(); 
//jquery api
$("#dllink")[0].click();

星期三, 3月 13, 2013

[jQuery API] 偵測關閉網頁使用者點選ok或cancel

為了避免使用者在網頁處理中關閉網頁的話,可以綁定onbeforeunload事件來偵測,
但更進一步的應用,可能需要了解使用者到底是按ok還是cancel!!
找到以下這篇所用到的解法,有需要的人可以參考看看。

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?
The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling thereturn statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

$(function(){ 
 
 $(window).bind("beforeunload", function(e) {
  setTimeout(function() {
  
            setTimeout(function() {
                $("body").css('background-color', 'red').html("User click cancel button");
            }, 1000);
        },1);
        return 'are you sure';
 });
 
 //按ok處理
 $(window).unload( function () { 
  console.log('bye bye :)');
  
 } );
 
});

星期一, 1月 21, 2013

[jQuery API] beforeunload 偵測頁面關閉或刷新

有時候你需要偵測使用者刷新或關閉頁面進行一些處理,可以使用beforeunload事件。 //refesh page event
 $(window).bind("beforeunload", function() {
   return "Are you sure?";
 });

When you add return false, a confirmation dialog shows up, delaying the page unload. Meanwhile, the AJAX request finishes. When no return statement is included, the page will immediately unloads, terminating all active connections (and breaking your AJAX request). 

目前測試發現如果使用者按上一頁的話雖會執行這個事件,但卻會造成正在執行的連線中斷(例如:上傳) 不過眼尖發現這個confirm dialog的按鈕其實長的不一樣XD 


其他你感興趣的文章

Related Posts with Thumbnails