现在我正在更改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
找到,但这对我不利。我怎么解决这个问题?感谢
答案 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)
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;
Target
是关键字。我仍然会使用addEventListener
,因为它比内联事件更标准。此外(您现在不需要它)它本地发送this
关键字,它允许附加其他类似的事件而不会覆盖它们。
答案 2 :(得分:0)
使用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';
}