今天就稍為做一下筆記
以下,是將 checkbox 的 click Event 去呼叫 preventDefault
使得 checkbox 無法去繼續進行勾選的動作
範例中,也有移除 preventDefault 及 模擬一個 click 的動作
以下是 html 碼
<input type="checkbox" id="checkbox"/><label for="checkbox">Checkbox</label> <br />
<input type="button" onclick="simulateClick();" value="Simulate click"/>    <br />
<input type="button" onclick="addHandler();" value="Add a click handler that calls preventDefault"/> <br />
<input type="button" onclick="removeHandler();"value="Remove the click handler that calls preventDefault"/> <br />
以下是 JavaScript 碼
    function preventDef(event) {
        event.preventDefault();
    }
    function addHandler() {
        document.getElementById("checkbox").addEventListener("click", preventDef, false);
    }
    function removeHandler() {
        document.getElementById("checkbox").removeEventListener("click", preventDef, false);
    }
    function simulateClick() {
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        var cb = document.getElementById("checkbox"); 
        var canceled = !cb.dispatchEvent(evt);
        if(canceled) 
        {
            // Some handler called preventDefault
            alert("canceled");
        } else {
            // None of the handlers called preventDefault
            alert("not canceled");
        }
    }
以上範例參考自:https://developer.mozilla.org/samples/domref/dispatchEvent.html
這種攔截事件,讓我想到,n個日子前
拍賣網站很流行釣魚,此方式也可以在使用者連結外部網站時
可以先停止 a link 的執行
範例程式碼,如下:
 <a href="http://www.google.com.tw">google</a> <br />
 <a href="http://tw.yahoo.com">yahoo</a> <br />
 <a href="http://tw.msn.com">msn</a> <br />
 <script type="text/javascript"> 
 function stopDefault( e ) { 
  if ( e && e.preventDefault ) 
   e.preventDefault(); 
  else 
   window.event.returnValue = false; 
  return false; 
 }  
 //自製一個 chklink Plugin 元件
 (function($) {
  $.fn.chklink = function() {
   return this.each(function() {
    $(this).click(function (e) {
     stopDefault(e);
     if( confirm("Notice !! \n U will link to" + this.href + "\n Are you sure ? ") )
     {
      window.open(this.href); //開新視窗
     }
    });
   });
  };
  //將所有 a 元件加上 chklink
  $('a').chklink();
 })(jQuery);
 </script>
事實上,好像也不一定要用 preventDefault也可以達到相同效果
將 click function 修改如下 :
//stopDefault(e);
if( confirm("Notice !! \n U will link to" + this.href + "\n Are you sure ? ") )
{
  window.open(this.href); //開新視窗
}else{
  return false; 
}
 
沒有留言:
張貼留言