2011-09-23 35 views
0

下午所有關聯數組作爲FO事件處理程序的對象使用數據

我有一些數據 -

var searchwithin = [ 
{id:"clearwithin", type:"button"}, 
    {id:"search_radius", type:"select"}, 
    {id:"for_lease" ,type:"checkbox"}, 
{id:"for_sale", type:"checkbox"}, 
]; 

這是將要顯示和隱藏PVC門依賴於被點擊了什麼(這,只有一小部分數據片段

我已經摸索出如何檢查type屬性,我想知道的是:

如果類型是按鈕,我如何訪問該項目的id值,然後生成一個點擊函數,以便使用該id作爲按鈕的名稱來將該函數與之關聯。

在此先感謝

菲爾

回答

0

首先,在表中的最後一個項目之後刪除逗號修復您的searchwithin表中的語法錯誤。這會在IE6/IE7中導致錯誤。

然後,您可以使用此代碼來翻檢searchwithin陣列找到id爲適當type,然後設置一個點擊事件處理程序爲id

var searchwithin = [ 
    {id:"clearwithin", type:"button"}, 
    {id:"search_radius", type:"select"}, 
    {id:"for_lease" ,type:"checkbox"}, 
    {id:"for_sale", type:"checkbox"} 
]; 

function findIdByType(target) { 
    for (var i = 0; i < searchwithin.length; i++) { 
     if (searchwithin[i].type === target) { 
      return(searchwithin[i].id); 
     } 
    } 
} 

var id = findIdByType("button"); 
if (id) { 
    $("#" + id).click(function() { 
     // do whatever you want to do on the click function here 
    } 
}); 

我注意到你的表有兩個條目type:checkbox。上述代碼建議將僅返回並在第一個條目上運行。如果您想爲這兩個ID設置點擊處理程序,那麼代碼或表格將不得不進行修改。如果這是所有表被用於,它可以改變爲一個選擇器(它可以包含多個id),如下所示:

var searchwithin = [ 
    {id:"#clearwithin", type:"button"}, 
    {id:"#search_radius", type:"select"}, 
    {id:"#for_lease, #for_sale", type:"checkbox"} 
]; 

function findSelectorByType(target) { 
    for (var i = 0; i < searchwithin.length; i++) { 
     if (searchwithin[i].type === target) { 
      return(searchwithin[i].id); 
     } 
    } 
} 

var selector = findSelectorByType("button"); 
if (selector) { 
    $(selector).click(function() { 
     // do whatever you want to do on the click function here 
    } 
}); 
0

串連「#」和id屬性,並使用生成的字符串作爲一個選擇。

$.each($.grep(searchwithin, function(i) { return i.type=='button'; }), 
    function() { 
     var item = this; 
     $('#'+this.id).bind('click', function(e) { 
      alert('clicked: ' + item.id +' '+ item.type); 
     }); 
    }); 

考慮使用選擇器來查找元素而不是ID映射。

$('input[type="button"].search').bind('click', onSearch); 
相關問題