我的第一篇文章中提供了一个代码:Need help about a function
我修改了这段代码并试着像我想要的那样工作。但是我在某一点上陷入困境。
JSfiddle LINK:http://jsfiddle.net/saifrahu28/qzKWD/
以下是代码:
HTML
<button id="createDiv">Start</button>
<div id="results"></div>
CSS
#createDiv, #results span { cursor: pointer; }
#results div {
background: #FFA;
border: 1px solid;
width:auto;
}
#results input[type=text] {
border: none;
display: none;
outline: none;
}
JS
// Call for document .onload event
$(function() {
// Normal Click event asignement, same as $("#createDiv").click(function
$("#createDiv").on("click", function(e) {
// Simply creating the elements one by one to remove confusion
var newDiv = $("<div />", { class: "new-folder" }), // Notice, each child variable is appended to parent
newInp = $("<input />", { name: "inpTitle[]",style:"display:block ;border:solid 1px #fa9a34", type: "text", value: "Unnamed Group", class: "title-inp" }).appendTo(newDiv),
newSpan = $("<span />", { id: "myInstance2",style:"display:none", text: "Unnamed Group", class: "title-span" }).appendTo(newDiv);
// Everything created and seated, let's append this new div to it's parent
$("#results").append(newDiv);
});
// the following use the ".delegate" side of .on
// This means that ALL future created elements with the same classname,
// inside the same parent will have this same event function added
$("#results").on("click", ".new-folder .title-span", function(e) {
// This hides our span as it was clicked on and shows our trick input,
// also places focus on input
$(this).hide().prev().show().focus();
});
$("#results").on("blur", ".new-folder .title-inp", function(e) {
// tells the browser, when user clicks away from input, hide input and show span
// also replaces text in span with new text in input
$(this).hide().next().text($(this).val()).show();
});
// The following sures we get the same functionality from blur on Enter key being pressed
$("#results").on("keyup", ".new-folder .title-inp", function(e) {
// Here we grab the key code for the "Enter" key
var eKey = e.which || e.keyCode;
if (eKey == 13) { // if enter key was pressed then hide input, show span, replace text
$(this).hide().next().text($(this).val()).show();
}
});
})
现在它做什么,当我点击开始按钮创建一个可以重命名的输入框并可以保存为文本。但是我想要的是..当我点击开始按钮时,它将创建输入使用BLINKING光标,现在不在这里。现在,当我点击它时它变得活跃。但我希望它应该开始闪烁当它被创建。可以使用任何jquery或java脚本吗?
答案 0 :(得分:2)
您需要使用focus()
事件。
$("#results").append(newDiv);
newInp.focus();
答案 1 :(得分:2)
你应该使用newInp.focus()
给文本框重点,但你可能还想把光标放在最后?
使用以下方法实现:
$.fn.setCursorToTextEnd = function() {
$initialVal = this.val();
this.val('');
this.val($initialVal);
};
然后做:
newInp.focus().setCursorToTextEnd();
对于Gavin G
,应该转到setCursorToTextEnd()
我已将此应用于您的小提琴 - http://jsfiddle.net/qzKWD/3/
答案 2 :(得分:1)