开发者

jquery alerts several times

Why does the following code cause jquery to alert 3 times?

.note_text is a class within .note_content.

   $('.note_content').click(function()  {
      var n开发者_运维百科ote_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');
         }   
      });

   });

When the outer div is highlighted I want the inner div (which contains the text) to be focused on.


This is due to action bubbling.

Adding a event.stopPropagation(); should fix that.

(remember - $('.note_content').click(function(event) {...)


$(note_text).blur(function() {

That line binds an event handler. Every time the element is blurred, that handler will run. You assign a new handler every time the click handler on .note_content is triggered, so you will have multiple alerts.

The way around this is to store data on the element, rather than in a closure.

$('.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');
    }
});

This way the handlers are only bound once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜