动态创建textarea和按钮

时间:2014-01-16 07:34:09

标签: javascript php jquery

我面临着为每个新段落创建动态文本区域和“添加”和“编辑”按钮的问题。

到目前为止我所掌握的事情的演示:

enter image description here

“添加”按钮用于创建新段落。用户应该看到textarea,在那里他们输入新段落的内容。当他们第一次点击“添加”按钮时,按钮上的文字将变为“保存”,第二次点击“保存”时,它应该将段落附加到div并为其分配一个唯一的ID,这将用于使用新的“添加”和“编辑”按钮引用它。

“编辑”按钮用于编辑单击“编辑”按钮的段落。为了使段落可编辑我正在使用jquery editable(jeditable)。以下是jeditable插件的适当链接:

enter image description here

enter image description here

从后端加载所有段落。使用PHP加载段落:

    <div class="paragraphs">
      <?php
      foreach($notes['children'] as $overview) :
        if ($overview['type'] == 'Paragraph') :
        ?>
          <div id="block1">
          <p class='edit1'><?php echo $overview['content']; ?></p>
          <p>
            <?php if (isset($subject) && $subject==true) : ?>
              <div id="para1">
                <p><textarea cols="40" rows="2" id="textarea1"></textarea></p>
                <button id="add1" class="add1 success tiny">Add</button>
                <button id="startEdit1" class="canEdit1 tiny">Edit</button>
              </div>
            <?php endif; ?>
          </p>
          </div>
        <?php endif; ?>
      <?php endforeach; ?>
    </div>

“添加”和“修改”按钮功能:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/teachers/js/jquery.jeditable.min.js"></script>
<script>
    var $subject_id = "<?php echo $subject_id ?>";
    var $teacher_id = "<?php echo $teacher_id ?>";

    // Define our elements
    var $lock = false;
    //Make the elements editable
    function makeThingsEditable() {
        $editables.editable({
            emptyMessage : '<em>Please write something...</em>',
            callback : function( data ) {
                $info.hide();
                $info.eq(0).show();
            }
        });
    }

    function ajaxRequest(data, method_url, request_type) {
      $.ajaxSetup({
          beforeSend: function(xhr) {
              xhr.setRequestHeader('HTTP/1.1', '200');
          }
      });

      var eurl = "<?php echo base_url(); ?>edit_flow/" + method_url;
      var params = 'inputJson=' + data; 

      var post = $.ajax({
        type: request_type,
        url: eurl,
        data: params,
        success: function(result) {
          console.log('result: '+result);
          console.log('data: '+params);
        },
        async: false
      });

      //alert(post.responseText);
      return post.responseText;
      console.log(post.responseText);
    }

    // Edit paragraph button
    // Button that toggles the editable feature 
    var i = 1;
    var $editables = $('.edit'+i);
    $('.canEdit'+i).click(function() {
        if( $editables.is(':editable') ) {
            //need to call save action here and pass in updated JSON
            if ($(this).text() == 'Save changes')
            {
              var text = $(".edit"+i).text();

              // ajax request
              var datum = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
              ajaxRequest(datum, 'editNotes', 'POST');  // POST request on editNotes
              ajaxRequest(datum, 'loadNotes', 'GET');  // GET request on loadNotes

              // jquery request
              $.get( "<?php echo base_url(); ?>edit_flow/loadNotes", function( data ) {
                var data = '{"subject_id":'+$subject_id+', "teacher_id":'+$teacher_id+', "editedContent":"'+text+'"}';
                //console.log(data);
                alert( data );
              });
            }

            $editables.editable('destroy');
            this.innerHTML = 'Edit';
            i++;
        } else {
            makeThingsEditable();
            this.innerHTML = 'Save changes';
            // TODO h4kl0rd: make $editables selectable 
        }
    });

    // Add paragraph button

    i = 1;
    $('#textarea'+i).hide();
    $('#add'+i).click(function(){
      if ( $(this).text() == "Add" ) {
        $('#textarea'+i).show();
        $(this).text('Save');
        $('#textarea'+i).focus(function() {
            this.select();
        });
      }
      else if ( $(this).text() == "Save" ) {
        if ($('#textarea'+i).val() == ''){
          alert('Enter something...');
        } else {
          $(this).text("Add");
          $('#textarea'+i).hide();
          var overview = $('#textarea'+i).val();
          i++;
          $('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
        }
      }
    });


</script>

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

改变这些:

 $('.canEdit'+i).click(function() {
 $('#add'+i).click(function(){

到这些:

 $(document).on('click', '.canEdit'+i, function() {
 $(document).on('click', '#add'+i, function() {

在我看来,你的按钮是动态的,它们不能直接绑定事件。因此,您必须将事件委托给最接近的静态父级$('.paragraphs')$(document)本身,因为它始终可用。

因此,如果您使用最接近的静态父级,则必须将事件处理程序放在doc ready内,如果您使用的是$(document),则不需要它。

$(function(){
    var i = 1;
    var $editables = $('.edit'+i);

    $('.paragraphs').on('click', '.canEdit'+i, function() {
         // all your edit stuff
    });

    $('.paragraphs').on('click', '#add'+i, function() {
         // all your addstuff
    });

});