2012-02-07 19 views
0

我有一個自定義上下文菜單腳本,用於多個DOM元素。當顯示元素時,我需要附加上下文菜單,並在未聚焦時分離它。我需要它被包含在一個函數中,以便我可以傳遞一個對象用於上下文菜單項目的點擊功能。我怎麼寫這個,這樣我就不必在每次顯示時重新創建DOM元素了?這是我到目前爲止有:自定義jQuery上下文菜單優化

function showCardContext(card) 
{ 
    cardContext = $('<ul>').css({'position': 'absolute', width: '150px', 'z-index': 5}).append(
     $('<li>').append($('<a href="#">').html('Flip Over')).click(function(){/* do something with card here */}), 
     $('<li>').append(
      $('<a href="#">').html('Counters'), 
      $('<ul>').append(
       $('<li>').append($('<a href="#">').html('Increment')).click(function(){/* do something with card here */}), 
       $('<li>').append($('<a href="#">').html('Decrement')).click(function(){/* do something with card here */}), 
       $('<li>').append($('<a href="#">').html('Clear')).click(function(){/* do something with card here */}) 
      ) 
     ), 
     $('<li>').append($('<a href="#">').html('Make Note')).click(function(){/* do something with card here */}), 
     $('<li>').append(
      $('<a href="#">').html('Send To'), 
      $('<ul>').append(
       $('<li>').append($('<a href="#">').html('Hand')).click(function(){/* do something with card here */}), 
       $('<li>').append(
        $('<a href="#">').html('Deck'), 
        $('<ul>').append(
         $('<li>').append($('<a href="#">').html('Shuffle In')).click(function(){/* do something with card here */}), 
         $('<li>').append($('<a href="#">').html('On Top')).click(function(){/* do something with card here */}), 
         $('<li>').append($('<a href="#">').html('On Bottom')).click(function(){/* do something with card here */}), 
        ) 
       ).click(function(){/* do something with card here */}), 
       $('<li>').append($('<a href="#">').html('Discard')).click(function(){/* do something with card here */}), 
       $('<li>').append(
        $('<a href="#">').html('Land of Redemption'), 
        $('<ul>').append(
         $('<li>').append($('<a href="#">').html('Yours')).click(function(){/* do something with card here */}), 
         $('<li>').append($('<a href="#">').html('Opponents')).click(function(){/* do something with card here */}) 
        ) 
       ).click(function(){/* do something with card here */}) 
      ) 
     ), 
     $('<li>').append($('<a href="#">').html('Remove From Play')).click(function(){/* do something with card here */}), 
     $('<li>').append($('<a href="#">').html('Relenquish Control')).click(function(){/* do something with card here */}) 
    ).appendTo($('body')).menu().hide(); 

    $(card.view).bind('contextmenu', function(e){cardContext.css({'left':e.pageX,'top':e.pageY}).show();}); 

    $(document).bind('click', function(e) { 
     var $clicked = $(e.target); 

     // Hide Deck Menu 
     if ((!$clicked.hasClass('card') && !$clicked.parent().hasClass('card')) || e. 
     { 
      cardContext.hide(); 
     } 

    }); 
} 

回答