2014-05-21 57 views
-1

我的頁面上的各種元素都有內容可編輯標籤。將一個on事件添加到e.currentTarget?

當他們被點擊我這樣做:

$('[contenteditable]').on('click', this.edit); 

p.edit = function(e) { 

    console.log(e.currentTarget); 
    e.currentTarget.on('keydown', function() { 
     alert("keydown..."); 
    }); 


}; 

我得到的當前目標確定,但是當我嘗試的keydown添加到它,我得到的錯誤:

Uncaught TypeError: undefined is not a function 
+0

嗯,你要確保多個事件不附? – epascarello

回答

2

這是一個原生的DOM元素,你就必須把它包在jQuery的

$(e.currentTarget).on('keydown', function() { 
    alert("keydown..."); 
}); 

e.currentTarget應該等於this裏面的事件處理程序,哪個更常用?

這是一個有點分不清是如何工作的,但我想我會做類似

$('[contenteditable]').on({ 
    click : function() { 
     $(this).data('clicked', true); 
    }, 
    keydown: function() { 
     if ($(this).data('clicked')) 
      alert("keydown..."); 
    } 
}); 

Demo

+0

謝謝,但警報不會爲我解僱。 – panthro

+1

'p'等於'this',它看起來很奇怪嗎?打開控制檯並檢查錯誤 – user3649503

+0

控制檯上沒有錯誤。 – panthro

0

你需要用的e.currentTarget(這是一個天然的DOM元素) jQuery中,因爲 「對」 事件是一個jQuery事件:

$(e.currentTarget).on('keydown', function() { 
    alert("keydown..."); 
}); 

編輯:

$('[contenteditable]').on('click', p.edit); 

p.edit = function(e) { 

    $(e.currentTarget).on('keydown', function() { 
     alert("keydown..."); 
    }); 
}; 

你定義p.edit$('[contenteditable]').on('click', p.edit);導致一個錯誤,因爲p.edit聲明on當它不存在。

如果你不知道,你要定義p.edit作爲函數表達式,這意味着你必須定義之前調用它。

1

第一個問題是你要使用DOM元素jQuery的方法。第二個問題是我不認爲你想綁定什麼點擊,但內容可編輯元素本身。

它也似乎不可思議被添加上點擊而不是全局偵聽器的事件。但是,這是基本的想法

$(this) //current content editable element 
    .off("keydown.cust") //remove any events that may have been added before 
    .on('keydown.cust', function(e) { //add new event listener [namespaced] 
     console.log("keydown"); //log it was pressed 
}); 
1

編輯:我在代碼中的失敗。現在它工作正常。

讓您的代碼,我提高到這樣一條:

$(function(){ 
    $('[contenteditable]').on('click', function(){ 
     p.edit($(this)); 
    }); 
}); 

var p = { 
    edit: function($e) { 
     console.log($e); 
     $e.on('keydown', function() { 
      console.log($(this)); 
      alert("keydown..."); 
     }); 
    } 
} 

可以check it at jsFiddle

+0

'$(this)'不是您認爲的那樣...您只是將一個keydown事件添加到文檔中。 – epascarello

+0

大聲笑你是對的,thx通知我@epascarello,後更新做得很好:) – kosmos