2012-12-26 29 views
0

我有這樣的代碼:如何爲多個元素綁定事件?

var li = $('<li>',{ 
    html : '<div class="header">' + header + '</div><div class="subheader">' 
      + sub_header + '</div><div class="optkey">' + option_key + '</div>' 
      }); 

var tmpLi = li.first()[0].firstChild; 

if(active) { 
    li.bind({ 
     mousedown: function(event) { 
      console.log("mousedown"); 
      event.stopPropagation(); 
      select_box.find('.sbContent').html($(this).find('.header').html()); 
      select_box_disabled.find('.sbContent').html($(this).find('.header').html()); 
      select_options_container.trigger('hide'); 
      // *FINISH* need to update the original select input with the new value 
      var key = $(this).find('.optkey').html(); 

      select_source.find('option:selected').removeAttr('selected'); 
      select_source.find('option:eq(' + key + ')').attr('selected', 'selected').change(); 
      return false; 
     } 

    }), 

    tmpLi.bind({ 
     keypress: function(event) { 
      console.log("keypress"); 
      event.stopPropagation(); 
      select_box.find('.sbContent').html($(this).find('.header').html()); 
      select_box_disabled.find('.sbContent').html($(this).find('.header').html()); 
      select_options_container.trigger('hide'); 
      // *FINISH* need to update the original select input with the new value 
      var key = $(this).find('.optkey').html(); 

      select_source.find('option:selected').removeAttr('selected'); 
      select_source.find('option:eq(' + key + ')').attr('selected', 'selected').change(); 
      return false; 
     } 

    }); 
} 

之前,我添加了tmpLi.bind塊,它工作得很好。現在,我在Firebug中出現這個錯誤:

TypeError: tmpLi.bind is not a function

keypress: function(event) {

如何將一個唯一事件綁定到同一if語句中的兩個元素?或者tmpLi不是一個有效的元素? (tmpLi返回HTML字符串<div class="header">

回答

2

tmpLi不是jQuery對象(只是一個DOM元素),並因此它沒有bind方法。

您可以在分配改寫爲tmpli分配一個jQuery對象,而不是:

var tmpLi = li.first().children().first(); 
+0

那麼,我需要做的就是隻包含div元素,我需要目標的對象? – EmmyS

+0

@EmmyS:查看更新 - 'first()將返回一個元素。 –

+0

謝謝。事件處理實際上不會完全相同;這只是剪切和粘貼,看看它是否會承認按鍵。 – EmmyS

相關問題