0

下午所有

我有一些数据-

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

它将根据单击的内容显示和隐藏信息(这只是数据的一小部分。

我已经弄清楚了如何检查 type 属性,我想知道的是以下内容:

如果类型是按钮,我如何访问该项目的 id 值,然后生成一个点击函数,以便使用 id 作为按钮的名称来关联该函数。

提前致谢

菲尔

4

2 回答 2

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
    }
});
于 2011-09-23T14:57:36.053 回答
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);
于 2011-09-23T14:41:53.153 回答