繁体   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