[英]jquery - get the id of the closest element?
這是我的代碼,用於在單擊輸入時編輯輸入,然后保存在數據庫中。
$(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 根本沒有檢索它。 我只想從中檢索 id 中的數字,但是它不起作用。 我一直在嘗試幾種解決方案,最后一個也不起作用
<div id="comments">
<div class="commentbox" id="comment-90">...</div>
<div class="commentbox" id="comment-91">...</div>
</div>
這部分代碼基本上是有問題的:
var div_id = $(this).closest('#commentbox').attr('id');
首先,您試圖從document
中獲取最接近的元素,因為this
指向您代碼的那部分中的document
(您的意思可能是event.target
)。 其次,您試圖找到最接近id == 'commentbox'
元素,因為這就是#<selector>
的意思。 您應該為此目的使用一些其他屬性 - 可能最好是一些 class 選擇器,然后在其上使用.attr('id')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.