2011-09-23 31 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); 
相关问题