简体   繁体   English

比较 javascript 中的 2 个元素的最有效方法是什么?

[英]What's the most efficient way to compare 2 elements in javascript?

Here's my code to make txtKeyword input to have focus when the user presses a key.这是我的代码,用于在用户按键时使 txtKeyword 输入具有焦点。

var txtKeyword = document.getElementById("txtKeyword");
...
document.addEventListener("keypress", function(event) {
    if(event.srcElement == txtKeyword)
    {
        return;
    }
    txtKeyword.focus();
}

I need to compare the elements to know if the message sender is the element on which I want to focus fail.我需要比较元素以了解消息发送者是否是我想要关注的元素失败。

event.srcElement == txtKeyword
event.srcElement.id == "txtKeyword"
event.srcElement === txtKeyword

These comparison which is faster?这些比较哪个更快? Considering id is a string, if the element's id is long, this way would not a ideal way.考虑到 id 是一个字符串,如果元素的 id 很长,这种方式不是理想的方式。

My guess is that the last one should be the fastest because it doesn't do any coercion.我的猜测是最后一个应该是最快的,因为它不做任何强制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 比较两个对象的值的最有效方法是什么? - What's the most efficient way to compare values of two objects? 什么是在IE8 +中追加元素的最有效方法? - what's the most efficient way to append elements in IE8+? 使用JavaScript评估字符串是否是回文符的最有效方法是什么? - What's the most efficient way to evaluate if a string is a palindrome using Javascript? 在Java中通过字符串的最有效方式是什么? - What is the most efficient way to go through string's chars in Javascript? 在JavaScript中,将标签转换为链接的最有效方法是什么? - In javascript, what's the most efficient way to I turn tags into links? 在Javascript中创建嵌套div的最有效方法是什么? - What is the most efficient way to create nested div's in Javascript? 在 JavaScript 中处理显示对话框/模式的最有效方法是什么? - What's the most efficient way to handle displaying a dialog/modal in JavaScript? 等待Java中异步函数调用的最有效方法是什么? - What's the most efficient way to wait for an asynchronous function call in Javascript? 在Javascript中声明函数的最有效方法是什么? - What is the most efficient way to declare functions in Javascript? 在Javascript中实现GroupBy的最有效方法是什么? - What is the most efficient way to implement GroupBy in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM