问题描述
|
为什么以下代码导致jquery发出3次警报?
.note_text
是.note_content
内的一个类。
$(\'.note_content\').click(function() {
var note_text = $(this).find(\".note_text\");
$(note_text).focus();
// save its contents:
var original_text = note_text.html();
$(note_text).blur(function() {
if (note_text.html() !== original_text)
{
alert(\'Not the same\');
}
});
});
当外部div突出显示时,我希望内部div(包含文本)被关注。
解决方法
$(note_text).blur(function() {
该行绑定了一个事件处理程序。每当元素模糊时,该处理程序就会运行。每次触发ѭ1上的单击处理程序时,您都会分配一个新的处理程序,因此您将有多个警报。
解决此问题的方法是将数据存储在元素上,而不是存储在闭包中。
$(\'.note_content\').click(function() {
$(this).find(\'.note_text\').data(\'oldText\',node_text.html()).focus();
});
$(\'.note_text\').blur(function() {
if ($(this).html() !== $(this).data(\'oldText\')) {
alert(\'not the same\');
}
});
这样,处理程序仅绑定一次。
, 这是由于动作冒泡。
添加ѭ6可以解决此问题。
(记住-$(\'.note_content\').click(function(event) {...
)