javascript事件,onfocus

时间:2015-02-21 09:53:16

标签: javascript events

现在我正在更改onfocus(onclick等)事件的默认行为,如下所示:

<div onfocus="my(this);"> </div>
function my(e){
    e.style.backgroundColor = "red";//here we do not use getElementById
}

在我需要从javascript附加事件之前,这很有效。我们当然可以使用addEventListener("focus", my),但在这种情况下,我们不会发送this值,而是需要getElementById找到,但这对我不利。我怎么解决这个问题?感谢

3 个答案:

答案 0 :(得分:1)

试试这个。将您的HTML更改为:

<div onclick="my(event);"> test</div>

你的JS对此:

function my(e){
    e.target.style.backgroundColor = "red";//here we do not use getElementById
}

e.target是接收事件的元素。

答案 1 :(得分:0)

&#13;
&#13;
    document.querySelector("div").addEventListener("click", my, false); //select the only div

    function my(e){
        e.target.style.backgroundColor = "red";//here we do not use getElementById
    }
&#13;
<div> Test div </div>
&#13;
&#13;
&#13;

Target是关键字。我仍然会使用addEventListener,因为它比内联事件更标准。此外(您现在不需要它)它本地发送this关键字,它允许附加其他类似的事件而不会覆盖它们。

答案 2 :(得分:0)

Working example here

使用tabindex 为要使用焦点的每个div添加一个类。 Tabindexes可以使div成为焦点

<div class="sofocus" tabindex="0">

现在你可以添加eventlistener

var focusDivs = document.querySelectorAll('.sofocus');
for(var i = 0; i < focusDivs.length; i++){
  var div = focusDivs[i];
}

使用事件绑定每个div

div.addEventListener("focus", styleItRed);

还因为不再关注

div.addEventListener("blur", removeColor);

考虑到这一点,你可以创建函数

function styleItRed(){
    this.style.color = 'red';
}

function removeColor(){
    this.style.color = 'inherit';
}