[英]class .on(click) failing when html inside is changed
第一次我有一個.on(click)可以正常工作,但是第二次卻失敗了,其方式如下。 這是代碼:
$('.inline-edit').on('click', function() {
if (!$(this).find(':input').length) {
var current_val = $(this).find('span').html();
$(this).html('<input type="text" class="txt" maxlength="27" value="' + current_val + '"/>');
//On outside click, cancel
$(this).unbind('clickoutside').bind('clickoutside', function(event) {
cancelEdit($(this), current_val);
})
}
});
單擊具有內聯編輯類的<td>
,將獲得內部范圍中的值,並啟用輸入。 這樣,用戶可以進行內聯編輯。 當用戶在<td>
之外單擊時,將取消編輯,並調用cancelEdit(),即:
function cancelEdit(element, value) {
$(element).html('<span>' + value + '</span><img id="pencil_edit" src="/images/pencil_edit.png">');
}
cancelEdit函數將<td>
返回其原始形式,即:
<td class="inline-edit">
<span>abcdpqsdfsdfsdfrstuvwxyz<?php echo $i?></span>
<img id="pencil_edit" src="/images/pencil_edit.png"/>
</td>
問題在於,在調用cancelEdit之后,現在當用戶單擊<td>
,如果他們單擊<span>
部分(文本),則.on('click')
函數將無法正常工作,因為正在獲取<span>
元素,而不是<td>
。 但是,即使html與第一次完全相同,這也只會在第二次發生。 為什么會這樣呢?
我認為你需要stopPropagation
傳播 :
$('.inline-edit').on('click', function(ev) {
var td = $(this);
if (!td.find(':input').length) {
var current_val = td.find('span').html();
td.html('<input type="text" class="txt" maxlength="27" value="' + current_val + '"/>');
//On outside click, cancel
td.one('clickoutside', function(event) {
cancelEdit(td, current_val);
})
}
ev.stopPropagation();
});
function cancelEdit(element, value) {
$(element).html('<span>' + value + '</span><img id="pencil_edit" src="http://placehold.it/20">');
}
我還為該元素設置了一個變量,因為確實不需要一遍又一遍地調用$(this)
。
嘗試這個:
$('body').on('click', '.inline-edit', function() {
if (!$(this).find(':input').length) {
var current_val = $(this).find('span').html();
$(this).html('<input type="text" class="txt" maxlength="27" value="' + current_val + '"/>');
//On outside click, cancel
$(this).unbind('clickoutside').bind('clickoutside', function(event) {
cancelEdit($(this), current_val);
})
}
});
我接受了另一個答案,該答案有效,但這是上乘的:
$('.inline-edit').on('click', function(ev) {
var td = $(this);
if (!td.find(':input').length) {
var current_val = td.find('span').html();
td.html('<input type="text" class="txt" maxlength="27" value="' + current_val + '"/>');
//On outside click, cancel
td.unbind('clickoutside').bind('clickoutside', function(event) {
cancelEdit(td, current_val);
})
}
});
我從上面刪除了event.stopPropagation(),如果cancelEdit看起來像這樣,則不需要:
function cancelEdit(element, value) {
$(element).html('<span>' + value + '</span><img id="pencil_edit" src="/images/pencil_edit.png">');
$(element).unbind('clickoutside');
}
訣竅是解除Clickoutside的綁定,否則,即使使用新的html,它也仍然綁定到該元素。 希望對類似情況的人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.