jquery - positioning of cloned object
If the user hits return while in one of the given text input fields, I'm trying to insert a new, blank text input field right below it - and before the other existing ones. The code below works fine in appending it to the bottom of the container, but I'm struggling with how to place it directly below the selected input field.
Any 开发者_StackOverflowsuggestions?
JS
if (event.keyCode == 13) {
$(this).clone(true).val('').appendTo('#item_container').focus();
return false;
}
HTML
<div id="item_container">
<input type="text" class="list_item">
<input type="text" class="list_item">
<input type="text" class="list_item">
<input type="text" class="list_item">
</div>
if (event.keyCode == 13) {
$(this).clone(true).val('').insertAfter(this).focus();
return false;
}
Use after
$(this).after($(this).clone(true).val('')).focus();
or insertAfter
$(this).clone(true).val('').insertAfter(this).focus();
jQuery has a :focus
selector which can be used to find the item with focus, i.e.
$("#item_container input:focus")
use jQuery after or insertAfter for that ;)
var target = $(this)
var copy = target.clone();
target.after(copy)
copy.val('').focus();
or all at once:
$(this).after($(this).clone().val('').focus());
this sets the focus on and clears the new element
or
$(this).after($(this).clone()).val('').focus();
this sets the focus on and clears the old element
fiddle here
精彩评论