2012-12-26 30 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

相关问题