JavaScript EventListener未将事件变量传递给事件处理程序

我正在尝试使用事件变量来编辑元素的CSS。我收到的错误消息是,即使事件监听器应传递事件,事件也未定义。

感谢您的帮助


import com.squareup.moshi.Json


/**
 * Data is the main name of this class because there was no name for the main JSON Object of which stores was a sub-object of.
 * Therefore Data houses a List<Store> member that would hold all the actual stores
 */


data class Data(
    @field:Json(name = "stores") val stores: List<Store>
)

data class Store(
    val address: String,val city: String,val name: String,val latitude: String,val zipcode: String,val storeLogoURL: String,val phone: String,val longitude: String,val storeID: String,val state: String
)

solanum 回答:JavaScript EventListener未将事件变量传递给事件处理程序

您要在点击处理程序中添加keyup事件,这将在每次点击发生时添加新的侦听器功能,这是不对的! 将keyup事件处理函数带到其自己的函数中,并在SetNewBranch内部或任何需要的地方调用它一次。请参见下面的示例。 另外,要获取元素,您可以使用event.target

function attachKeyUpEvent() {
document.addEventListener("keyup",function(e){           
        let sel = window.getSelection();
        let ele = sel.anchorNode;

        ele.textContent = e.key;
        if(ele.textContent.trim()){
            ele.focus
//            setCursorToEnd(ele);    
        }
        ele.parentElement.style.backgroundColor = '#FFFFFF';   
        ele.parentElement.setAttribute("class","old");   
   });
}
    
function newClick(event){
    event.target.style.backgroundColor = '#ABAEAB';
}

function SetNewBranch(){
    let li_NewSpan = document.getElementsByClassName("new");

    for(let i = 0; i < li_NewSpan.length; i++){        
        if(!li_NewSpan[i].getAttribute("EventListener") && li_NewSpan[i].getAttribute("class") == "new"){          
            li_NewSpan[i].addEventListener("click",newClick,false);            
        }
    }
   attachKeyUpEvent();
}

SetNewBranch();
<ul>
<li class="new"> one </li>
<li class="new"> two </li>
<li class="new"> three </li>
</ul>

本文链接:https://www.f2er.com/2982726.html

大家都在问