I have a keypress handler bound to all input elements on a form, and I need to perform different operations depending on which element received the keypress. All 3 variations below work, but I'd like to know if one (or something else) is preferred and why.
$(':input').keypress(function(e) {
if($(this).attr('id') === 'foo') // option 1
console.log('foo');
if($(this)[0] === $('#bar')[0]) // option 2
console.log('bar开发者_运维百科');
if(e.target === $('#baz')[0]) // option 3
console.log('baz');
});
There are few elements on the page, so performance isn't really a concern. It's more of a stylistic/standards/readability issue.
Option #4:
$(':input').keypress(function(e) {
if(this.id == 'foo') console.log('foo');
});
this
will be a DOM element in the handler, no need for the jQuery object checks, just do a string comparison against the native .id
DOM property, it's clear, concise and the fastest - win, win here.
The nicest way is none of these. Use this.id
rather than $(this).attr('id')
for performance:
if (this.id == 'foo') {
Even nicer would be to use the ID in the selector, if what you are actually looking for is the input element with the ID foo
.
$('#foo').keypress(function(e) {
This will be substantially quicker than :input
.
精彩评论