1. 程式人生 > >DOM0級事件綁定之內聯onclick事件

DOM0級事件綁定之內聯onclick事件

function highlight .proto 方法 影響 報錯 scrip 事件 ttr

  DOM0級事件中比較常看到的這種綁定方法:

<input type="button" value="click me" onclick="show(this,type,event)">    ---代碼1   // 點擊按鈕谷歌下輸出:[input, "button", MouseEvent]

事件在DOM之前定義:

function show() {              ---代碼2
  console.log(Array.prototype.slice.call(arguments));
}

  

之前一直朦朦朧朧,不知道onclick中綁定的show事件是怎麽傳參數的~~~

show事件一般我們知道的是可以傳兩個參數:this和event,分別是綁定的這個DOM對象、發生的事件

但是這種綁定事件的原理實際上是這樣的:

function(){             ---代碼3
  with(document){
    with(this){
      // 元素屬性值
    }
  }
}

  在代碼1中,我傳了type參數,實際上訪問的正好是this.type,就是當前DOM元素的type屬性。DOM0級綁定事件的原理就是代碼3描述的,綜合起來可能就類似這樣:

  傳遞的參數a,先在this中找,即this.a,如果未定義,就在document中找,找不到就報錯

function show() {               ---代碼4
  with(document){
    with(this){
      // 元素屬性值
      // 實際操作代碼
    }
  }
}

  代碼1中傳的第1個參數this,這個不用說,都知道是當前的DOM對象;第2個參數type,就是會在this中找,看this有沒有這個屬性,沒有的話,就在document中找;第3個參數就是事件對象。函數裏傳參的順序和內容可以隨便改變的。

  ------------------------------第2種情況-----------------------------------

  就是表單情況:

<form action="">       ---代碼5
  <input type="text" name="username">
  <input type="button" value="click me" this="32" event="sd" onclick="show(this,getAttribute(‘this‘),type,event,getAttribute(‘event‘),username.value)">  

// 點擊按鈕谷歌下輸出:[input, "32", "button", MouseEvent, "sd",""]
</form>

  表單情況會增加一層邏輯,就是this.form:

function(){
  with(document){
    with(this.form){
      with(this){
        // 元素屬性值
        // 處理代碼
      }
    }
  }
}

  在代碼5中,先說說username.value這個參數,就是表單中可訪問的一個作用域this.form。傳入參數會先看this有沒有定義該屬性,有就傳入,沒有的話,就在this.form中找,沒有的話,最後在document中找。

  另外,我故意在DOM上寫了this、event的屬性,看怎麽樣才能訪問,會不會影響默認的this、event。驗證後發現,自定義的屬性只能通過getAttribute函數獲取到(做這個驗證只能說明我的js不紮實o(╥﹏╥)o)

DOM0級事件綁定之內聯onclick事件