2011-05-12 73 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