简体   繁体   English

jquery - 获取最近元素的 id?

[英]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. Var div_id 根本没有检索它。 And I want to retrieve only the number from the id from this however it does not work.我只想从中检索 id 中的数字,但是它不起作用。 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).首先,您试图从document中获取最接近的元素,因为this指向您代码的那部分中的document (您的意思可能是event.target )。 Secondly, you are trying to find the closest element with id == 'commentbox' , as this is what #<selector> means.其次,您试图找到最接近id == 'commentbox'元素,因为这就是#<selector>的意思。 You should use some other attribute for that purpose - probably best would be some class selector and then use the .attr('id') on it.您应该为此目的使用一些其他属性 - 可能最好是一些 class 选择器,然后在其上使用.attr('id')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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