jQuery找到location.href并用函数替换

时间:2011-05-12 22:19:48

标签: jquery

如果使用jQuery启用javascript,我将所有页面元素从单独的加载转换为Ajax页面。我做了大部分事情,但我需要检查的一件事是onclick / onchange事件。

我有这个:

    $("select").each(function(){
        if ($(this).attr('onchange')) {
            //CHECK FOR LOCATION.HREF
        }
        return false;
    });

需要改变:

location.href='/calendar-of-events/'+escape(this.options[this.selectedIndex].value)+'/5/2011/

成:

pageload('/calendar-of-events/'+escape(this.options[this.selectedIndex].value)+'/5/2011/')

我该怎么做?

感谢。

编辑:

我试过了:

    $("select").each(function(){
        if ($(this).attr('onchange')) {
            var ocval = $(this).attr('onchange');
            ocval = ocval.replace('location.href=','pageload(');
            ocval = ocval+')';
            $(this).attr('onchange',ocval);
        } 
        return false;
    });

但这不起作用。 onchange值是一个函数。

function onchange(event) {
    location.href = "/calendar-of-events/" + escape(this.options[this.selectedIndex].value) + "/5/2011/";
}

我该如何改变?

2 个答案:

答案 0 :(得分:1)

我建议你不要使用onchange属性,只需用jQuery绑定事件。

$("select").change(function(){
   pageload("/calendar-of-events/"+escape($(this).val())+"/5/2011/");
});

如果你不能这样做,那么我建议你删除onchange属性,并使用jQuery重新绑定事件。

$("select").each(function() {
    if($(this).attr('onchange')){
        // Get the onchange function
        var url = $(this).attr('onchange').toString()
            // Regex to extract the location.href
           .match(/location\.href\s?=\s?(['"].*['"])/);
        // If we found a match
        if(url !== null){
            this.onchange = null; // Remove onchange event
            $(this).change(function(){  // Rebind onchange
                // Eval the location.href string, setting "this" to the select element
                var urlstr = new Function('return '+url[1]).call(this);
                // Call pageload with our eval'd url
                pageload(urlstr);
            });
        }
    }
});

演示:http://jsfiddle.net/R6Zzb/10/

答案 1 :(得分:0)

Javascript提供了一大堆字符串操作,可以帮助您完成此操作。对于你提到的例子,一个简单的substr()可能会这样做。如果它更高级,您可能需要考虑使用正则表达式。

以下是一些帮助您入门的教程:

http://www.w3schools.com/jsref/jsref_substr.asp
http://www.w3schools.com/jsref/jsref_obj_regexp.asp