我有一个示例,我从之前的帖子中得到了这个。我正在尝试根据我的需要升级它,但是我失败了。我想这是因为我对jquery和JavaScripts缺乏了解。但我非常需要这个。
以下是 js小提琴中的现场演示:http://jsfiddle.net/qzKWD/5/
我现在拥有的内容:
在那里你可以看到我有一个按钮。如果我单击按钮,它将打开Div with Editable输入,我可以在其中重命名输入并保存。您可以通过单击按钮创建许多div并根据需要重命名。
我想做什么
我试图做的是,我在那里添加了一个“X”文本。当我单击“START”按钮时,使用输入创建新div以更改名称,也使用此“X”文本。我主要尝试的是..在重命名之前我输入如果我没有那个div我可以通过单击“X”文本删除输入div。这意味着“X”将作为该Div的结束。但我没有找到任何方法来做到这一点。可能是因为我缺乏知识。如果有任何解决方案或方式,那将是优秀的。
我的代码:
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);
// 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();
}
});
})
答案 0 :(得分:1)
只需添加以下代码
即可clickToCancle.click(function() {
$(newDiv).remove();
});
后,
clickToCancle = $("<a />", { text: "X", class: "clickToCancleIcon" }).appendTo(newDiv);
或者您可以通过
完成此操作clickToCancle = $("<a />", { text: "X", class: "clickToCancleIcon" }).appendTo(newDiv).click(function() {
$(newDiv).remove();
});
查看实时DEMO