javascript - jquery pass parameters on mutual functions -
i have 2 functions in jquery change div
textarea
on click , making div
on blur. need save id
of div
, use in function nested. how can pass id
between these 2 functions? code, detects th id
event
function divclicked(id) { console.log("click"); var divhtml = $(this).html(); var editabletext = $("<textarea />"); editabletext.val(divhtml); $(this).replacewith(editabletext); editabletext.focus(); // setup blur event new textarea var iden = $(this).attr("id"); editabletext.blur(id, editabletextblurred); } function editabletextblurred(id) { console.log("blur"); var html = $(this).val(); var viewabletext = $("<div>"); viewabletext.html(html); $(this).replacewith(viewabletext); var descr = viewabletext.html(); // setup click event new div cool_function(id, descr); $(viewabletext).click(id, divclicked); }
a much better approach use delegated event handlers switch element between types, this:
$(document).on('click', 'div.switch', function() { var $textarea = $('<textarea />', { class: 'switch', html: $(this).html(), id: this.id }); $(this).replacewith($textarea); $textarea.focus(); }).on('blur', 'textarea.switch', function() { var $div = $('<div />', { class: 'switch', html: this.value, id: this.id }); $(this).replacewith($div); cool_function(this.id, this.value); }); function cool_function(id, html) { // logic here... console.log(id, html); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="switch" id="foo">foo <strong>bar</strong></div> <div class="switch" id="foo">fizz buzz</div>
the benefit of method work instance of div.switch
in html no amendments js, , it's 2 event handlers instead of having add/remove them each time elements swapped.
you go further , use contenteditable
div, depends on how page structured, , how server setup receive data.
wiki
Comments
Post a Comment