我有一个示例,我从之前的一篇文章中得到了这个。我正在尝试根据我的需要升级它,但我失败了。我想这是因为我缺乏 jquery 和 JavaScripts 方面的知识。但我非常需要这个。
我现在拥有的:
在那里你可以看到我有一个按钮。如果我单击该按钮,它将打开一个带有可编辑输入的 Div,我可以在其中重命名输入并保存。您可以通过单击按钮创建许多 div 并根据需要重命名。您也可以随时再次单击文本以更改名称。
我想要做什么
我想做的是,我在那里添加了一个“编辑”文本。
我主要尝试的是..如果我创建一个 DIV 并尝试再次重命名,而不单击文本以带来编辑模式。我想点击 EDIT text 来带来 Edit mode 。单击名称不应带来任何编辑模式。
我没有找到任何方法来做到这一点。可能是因为我缺乏知识。如果有任何解决方案或方法,那就太好了。
我的代码:
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;
}
.clickToCancleIcon{
float: right;
}
.new-folder{
height:30px;
float:left;
}
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 ;float:left; border:solid 1px #fa9a34", type: "text", value: "Unnamed Group", class: "title-inp" }).appendTo(newDiv),
newSpan = $("<span />", { id: "myInstance2",style:"display:none; float:left;", text: "Unnamed Group", class: "title-span" }).appendTo(newDiv),
clickToCancle = $("<a />", { text: "X", class: "clickToCancleIcon" }).appendTo(newDiv),
clickToEdit = $("<span />", { text: "Edit" , style:"float:right; margin:0px 5px;" ,
class: "clickToEdit" }).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();
}
});
})