В частности, я занимаюсь добавлением многих обработчиков событий при каждом щелчке элемента.
$(".container-items").on('click', '.item', function(event){
//show modal
$("#modal-background, #modal").show();
//get the current item contents and store it in a variable
var itemContent = $(event.currentTarget).text();
//populate textarea content with current "itemContent"
$("#editableText").val(itemContent);
//when user clicks cancel
$(".cancel").on("click", function(){
$("#editableText").val("");
$("#modal-background, #modal").hide();
$(".cancel").off("click");
$(".update").off("click");
});
//when user clicks update
$(".update").on("click", function() {
var newItemContent = $("#editableText").val();
$(event.currentTarget).text(newItemContent);
$("#modal-background, #modal").hide();
$(".update").off("click");
});
});
Вот мой jsfiddle: http://jsfiddle.net/3aa4T/
Вот мой HTML:
<div class="add-item-wrapper">
<div class="textbox">
<input id="item-value" type="text" />
</div>
<div class="add-item-btn">
<button>Add Item</button>
</div>
</div>
<div class="error">
<p>Sorry you have to add something to the list.</p>
</div>
<ul class="container-items">
</ul>
<button id="delete-all">Delete All Items</button>
<div id="modal-background"></div>
<div id="modal">
<div class="container-wrapper">
<div class="input-text">
<textarea id="editableText" rows="4" cols="20"></textarea>
</div>
<button class="update">Update</button>
<button class="cancel">Cancel</button>
</div>
</div>
Вот мой javascript:
$( document ).ready(function() {
var value = "";
//key up on keyboard event handler
$("#item-value").keyup(function( event ){
value = $("#item-value").val();
//if user pressed enter
if(event.which === 13){
if( !$(this).val() ){
$(".error").fadeIn("slow").fadeOut("slow");
} else {
$(".container-items").append("<li class='item'>" + value + "</li>");
$("#item-value").val("");
value = "";
}
}
});
//Submit item using "Add Item" button
$(".add-item-btn").click(function(){
value = $("#item-value").val();
//check to see if empty string
if ( value === "" ){
$(".error").fadeIn("slow").fadeOut("slow");
} else {
$(".container-items").append("<li class='item'>" + value + "</li>");
$("#item-value").val("");
value = "";
}
});
//Empty all items in "container-items" class
$("#delete-all").click( function(event){
$(".container-items").empty();
});
//click an item
$(".container-items").on('click', '.item', function(event){
//show modal
$("#modal-background, #modal").show();
//get the current item contents and store it in a variable
var itemContent = $(event.currentTarget).text();
//populate textarea content with current "itemContent"
$("#editableText").val(itemContent);
//when user clicks cancel
$(".cancel").on("click", function(){
$("#editableText").val("");
$("#modal-background, #modal").hide();
$(".cancel").off("click");
$(".update").off("click");
});
//when user clicks update
$(".update").on("click", function() {
var newItemContent = $("#editableText").val();
$(event.currentTarget).text(newItemContent);
$("#modal-background, #modal").hide();
$(".update").off("click");
});
});
});
Заметьте, я изменил также немного HTML и CSS, в основном я добавил модальный в него фоновый контейнер.
$(function() {
var $itemValue = $('#item-value'), // Cache your elements!
$modal = $("#modal-background"),
$editable = $("#editableText"),
$itemsContainer = $(".container-items"),
$selected; // Will keep track of the active (selected) item
$itemValue.keyup(function(e) {
if(e.which===13) $(".add-item-btn").click();
});
$(".add-item-btn").click(function() {
var value = $.trim( $itemValue.val() );
if (!value){
$(".error").fadeIn("slow").delay(800).fadeOut("slow");
} else {
$itemsContainer.append("<li class='item'>" + value + "</li>");
$itemValue.val("");
}
});
$("#delete-all").click( function(e) {
$itemsContainer.empty();
});
$itemsContainer.on('click', '.item', function(e) {
$selected = $(this);
$modal.show();
$editable.val( $selected.text() );
});
$(".cancel, .update").on("click", function(){
$modal.hide();
return this.className == 'update' ? // clicked '.update'?
$selected.text($editable.val()) : // yes
$editable.val(""); // no
});
});
.on()
и .off()
. Виноват. То есть я не вижу никакой причины использовать вкл / выкл, если только вы не храните эти данные немедленно на сервере, что может помешать быстрому щелчку ... или чему-то другому, запутавшему ваши данные. Так или иначе. Это более читабельно, и не добавляйте комментарии к коду, который говорит само за себя.
Я бы сделал раздел "добавить" форму... и просто использовал представление формы вместо обработчиков.keyup и button.click. Я сделал jsfiddle - http://jsfiddle.net/3aa4T/1/, при этом ключевые строки были
$("#add-item-form").submit(function(e){
e.preventDefault();
$("#item-value").keyup(function( event ){ var value = $(this).val(); ... $(this).empty()