简体   繁体   中英

jquery - get the id of the closest element?

This is my code which is used to edit an input when clicked on it and then save in the db.


    $(document).ready(function() {
      $('.editable').on('click', function() {
          var that = $(this);
          if (that.find('input').length > 0) {
              return;
          }
          var currentText = that.text();
          var $input = $('<input>').val(currentText);
          $(this).append($input);

          // Handle outside click
          $(document).click(function(event) {
              if(!$(event.target).closest('.editable').length) {
                  if ($input.val()) {
                      that.text($input.val());

                      var div_id = $(this).closest('#commentbox').attr('id');
                      div_id = div_id.replace('comment-', '');
                      alert(div_id);
                      $.post( "updateComment.php", {id: div_id,message: $input.val()})
                  }
                  that.find('input').remove();
              }
          });
      });
    });

Var div_id is not retrieving it at all. And I want to retrieve only the number from the id from this however it does not work. I've been trying several solutions and this last one isn't working either


    <div id="comments">
       <div class="commentbox" id="comment-90">...</div>
       <div class="commentbox" id="comment-91">...</div>
    </div>

This part of code is basically a problem:

var div_id = $(this).closest('#commentbox').attr('id');

Firstly, you are trying to get closest element from document as this points to document in that part of your code (you meant probably event.target instead). Secondly, you are trying to find the closest element with id == 'commentbox' , as this is what #<selector> means. You should use some other attribute for that purpose - probably best would be some class selector and then use the .attr('id') on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM