2011-05-12 122 views
0

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

我有这样的:

$("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

你回答了你自己的问题,好样的! – 2011-05-12 22:21:01

+1

最新的问题是什么? – Neal 2011-05-12 22:21:32

+0

我正在寻找代码来替换location.href,并围绕url包装pageload函数。问题是我需要确保onchange中没有其他功能。在这种情况下,我可以在字符串的末尾替换location.href = pageload(然后添加一个),但是如果还有其他东西,我需要找到location.href的结尾。 – fanfavorite 2011-05-13 12:59:50

回答

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/

+0

谢谢。这正在接近我所需要的。该url在IE9中返回一个匹配,但FF4则返回null。任何想法为什么? – fanfavorite 2011-05-13 16:12:03

+0

@fanfavorite:FF4在'location.href ='的等号前后增加了一个空格。我修复了代码,现在应该在FF4中工作。 – 2011-05-13 17:02:13

0

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

这里有几个教程,让你开始:

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

+0

谢谢。我在PHP中使用substr很多,但不幸的是,如果你看到我的文章中的编辑,我不知道如何操作初始函数。一旦我获得位置。href值,我可以重新创建函数并覆盖,但问题是从函数内部获取该值。 – fanfavorite 2011-05-13 13:22:03