簡體   English   中英

IE:onclick函數不能與'this'一起使用

[英]IE: onclick function doesn't work with 'this'

好的,所以我對IE 8及以下版本有一個奇怪的JS功能問題。 (誰猜到了)

在我的頁面的“腳本”部分定義了這個函數,它應該在點擊時改變節點元素的背景顏色:

function highlight(){
    if (this.style.backgroundColor != "rgb(163, 167, 334)"){
        this.style.backgroundColor = "rgb(163, 167, 334)";
    }
}

基本上,它說'如果它不是給定的backgroundColor,那就把它變成backgroundColor。'

為了喚起該方法,相同的'script'標簽還包含:

button.attachEvent('onmousedown', highlight);

出於某種原因,我在> IE9的開發人員工具控制台中不斷收到以下錯誤(在兼容模式下運行ie9為'ie8'):

SCRIPT5007:無法獲取屬性'backgroundColor'的值:object為null或undefined

我在IE8中使用'attachEvent'的方式與我在Firefox,Chrome和IE9中使用'addEventListener'的方式相同。 不幸的是,它似乎沒有以完全相同的方式表現。

我需要這個,因為我的客戶堅持使用IE8。

有什么建議么?


編輯/解決方案:發現了問題。 突出顯示函數引用'this'。 當attachEvent觸發時,它總是將'this'理解為'瀏覽器窗口',而不是接收操作的對象。 為了解決這個問題,有兩種方法:

element.onevent = function; (在我的情況下:button.onclick =突出顯示)

element [onevent] = function; (在我的情況下:按鈕[onclick] =突出顯示)

關於第二個變種,這是一個發現的獎勵(保持這里任何人磕磕絆絆)。 我將在這里分享:實際上可以通過編寫obj [onclick] = func來觸發click事件。 (在我的情況下是:“button [onclick] = highlight;”這很有用,因為它允許在必要時“傳入”事件的名稱。


謝謝大家的幫助! 案件結案。

可能會想要進行特征檢測

if (button.addEventListener){
 button.addEventListener( 'onmousedown', highlight, false );
}else if (button.attachEvent) {
 button.attachEvent( 'onmousedown', highlight );
}

這應該正確地注冊事件,以便訪問this 然而,如果this仍然是不確定的,你可能需要訪問event中,即對象。

function highlight(ev){
 if( typeof(ev) == "undefined" ){
  ev = window.event;
 }
 var target = ev.target || ev.srcElement;
 if (target.style.backgroundColor != "rgb(163, 167, 334)"{
  target.style.backgroundColor = "rgb(163, 167, 334)";
 }
}

顯然是一個奇怪的范圍問題。 考慮聲明一個變量來訪問而不是this (當我們不知道標記時很難在實踐中顯示):

var hl = document.getElementById('highlight');

function highlight(){
  if (hl.style.backgroundColor != "rgb(163, 167, 334)"{
    hl.style.backgroundColor = "rgb(163, 167, 334)";
  }
}

this.style.backgroundColor是指上下文,你的函數。 並且該函數沒有style.backgroundColor ,但是通過onmousedown附加到該函數的元素可能有。 另一種解決方案是:

document.getElementById('theElementInQuestion').onmousedown = function() {
  if (this.style.backgroundColor != "rgb(163, 167, 334)"{
    this.style.backgroundColor = "rgb(163, 167, 334)";
  }
}

我會使用JQuery,因為它具有出色的跨瀏覽器支持。 我使用$(“#button”)找到一個id =“button”的元素,但如果你想一次綁定更多的元素,你可以使用class =“。buttonClass”。

$("#button").click(highlight);

function highlight() {
    if (this.style.backgroundColor != "rgb(163, 167, 334)") {
        this.style.backgroundColor = "rgb(163, 167, 334)";
    }
};

我已經在幾個瀏覽器中測試了這個,包括IE8,它運行正常。

function highlight(){
if (this.style.backgroundColor != "rgb(163, 167, 334)"{
    this.style.backgroundColor = "rgb(163, 167, 334)";
}}

你錯過了一個“)”來關閉if的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM