0

This function wires the fourth instance of a dynamic control (a ListBox with select all/unselect all buttons):

function pageLoad() {

    $('#MainContent_lbx4_AllLB').live("click", function () {
        $('#MainContent_lbx4_RegionTypeLB').find('option').attr('selected', true);
    });

    $('#MainContent_lbx4_NoneLB').live("click", function () {
        $('#MainContent_lbx4_RegionTypeLB').find('option').attr('selected', false);
    });

}

I works but like I mentioned, it only works on the fourth instance. How I can I find how many of them there are on the page, and use that number to loop through and wire them all ?

4

2 回答 2

1

您可以修改您的事件,如下所示。这适用于您的控件的所有实例

$('[id^=MainContent_lbx]').live("click", function () {

    //split by underscore
    var main_id = $(this).prop('id').split('_'); 

    //pop last element in the array to check for AllLB or NoneLB
    var popLast = main_id.pop();

    //replace AllLB or NoneLB with RegionTypeLB
    main_id[2] = 'RegionTypeLB';
    var regionId = '#' + main_id.join('_');

    if(popLast == 'AllLB')
    {
        $(regionID).find('option').attr('selected', true);
    }
    else if(popLast == 'NoneLB')
    {
        $(regionID).find('option').attr('selected', false);
    }
});

jquery Documentation开始,从 jQuery 1.7 开始,不推荐使用 .live() 方法。使用 .on() 附加事件处理程序。旧版本 jQuery 的用户应该使用 .delegate() 而不是 .live()。它在 jQuery 1.9 中被移除

于 2013-09-23T15:27:56.250 回答
1

听起来你需要看看使用高级选择器 - http://api.jquery.com/category/selectors/

如果所有的列表框 id 都相似,你可以使用这样的东西

$("[id^='MainContent_lbx') 

这将针对 ID 以“MainContent_lbx”开头的所有元素

于 2013-09-23T15:07:47.977 回答