jQuery~在跟随它之前调整href

时间:2010-08-10 17:31:08

标签: javascript jquery dom

我有一系列复选框的链接,由于遗留代码,当用户点击复选框时,它的值会作为逗号分隔列表附加到href。

麻烦的是,现在我正在更新代码,我发现href的跟踪速度比href更快,因此排除了列表。

我尝试使用preventDefault()这很棒,但我不知道在更改href以包含所选值后如何继续默认操作。

我还应该提一下,将其更改为常规表单是不可行的,因为在提交后灯箱中设置了其他选项。 (不要问我为什么,这是我书中的精神错误)

到目前为止,我必须

$(function(){
    $('#cnt-area form table tbody').dragCheck();

    // I just split up the .each and .click to see if it mattered, which it doesnt
    $('.multi_assign_link').each(function(){
        $(this).click(function(e){

            e.preventDefault();
            var href = $(this).attr('href');

            $('#cnt-area form input:checkbox').each(function(){
                if($(this).attr('checked')){
                    if(href.search(','+$(this).val()) == -1){
                        href += ','+$(this).val();
                    }
                }else{
                    var s = ','+$(this).val();
                    s.toString();
                    href = href.replace(s, '');
                }
            });
            $(this).attr('href',href);
            // Continue to follow the link
            // Faking a user click here with $(this).click(); obviously throws a loop!
        });
    });
});

1 个答案:

答案 0 :(得分:5)

只需将位置设置为调整后的href值,然后从处理程序返回false,以避免使用原始链接。

$(function(){ 
    $('#cnt-area form table tbody').dragCheck(); 

    // I just split up the .each and .click to see if it mattered, which it doesnt 
    $('.multi_assign_link').each(function(){ 
        $(this).click(function(e){ 

            var href = $(this).attr('href'); 

            $('#cnt-area form input:checkbox').each(function(){ 
                if($(this).attr('checked')){ 
                    if(href.search(','+$(this).val()) == -1){ 
                        href += ','+$(this).val(); 
                    } 
                }else{ 
                    var s = ','+$(this).val(); 
                    s.toString(); 
                    href = href.replace(s, ''); 
                } 
            }); 
            location.href = href;
            return false;
        }); 
    }); 
});