\$\begingroup\$
\$\endgroup\$
2
$(document).on('dblclick', '#li', function () {
oriVal = $(this).text();
$(this).text("");
input = $("<input type='text'>");
input.appendTo('#li').focus();
});
$(document).on('focusout', 'input', function () {
if (input.val() != "") {
newInput = input.val();
$(this).hide();
$('#li').text(newInput);
} else {
$('#li').text(oriVal);
}
});
So far, I still can't do OOP in jQuery. Can you improve the above code?
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 10, 2013 at 11:00
-
\$\begingroup\$ Do not listen to such a ridiculous statement and instead have a look at these articles, they should greatly help you. alistapart.com/article/writing-testable-javascript addyosmani.com/resources/essentialjsdesignpatterns/book \$\endgroup\$plalx– plalx2013年10月11日 03:54:49 +00:00Commented Oct 11, 2013 at 3:54
-
\$\begingroup\$ Does this code work? You don't explain what you're trying to do, and the code and question title don't seem to match. \$\endgroup\$Daniel– Daniel2013年12月11日 14:39:49 +00:00Commented Dec 11, 2013 at 14:39
1 Answer 1
\$\begingroup\$
\$\endgroup\$
I wasn't sure how to answer this, so I went with what your code does...
- Scope your variables.
- Change your code to target all
li
instead of one element with the idli
. - Use
this
when events are triggered to make sure you have the correct element. - Remove the added elements instead of hiding them.
- Remember to call
on
using the smallest possible parent container. Possibly a<ul>
or<ol>
? - Use short circuiting where appropriate.
- Use
jQuery.parent()
to get the appended elements parent.
Putting all those change together:
var oriVal;
$("#parentUL").on('dblclick', 'li', function () {
oriVal = $(this).text();
$(this).text("");
$("<input type='text'>").appendTo(this).focus();
});
$("#parentUL").on('focusout', 'li > input', function () {
var $this = $(this);
$this.parent().text($this.val() || oriVal); // Use current or original val.
$this.remove(); // Don't just hide, remove the element.
});
Here's the JSFiddle.
answered Dec 11, 2013 at 15:08
default