2011-04-26 63 views
0

所以我有這樣的代碼:調用自定義的jQuery方法

<script language="javascript"> 
$(function(){ 
    function hellothere(strng){ 
     showalert(strng); 
    } 
    function showalert(showit){ 
     alert(showit); 
    } 
}); 
</script> 
<input type="button" onclick="hellothere('hi');" value="jquery"/> 

當我點擊按鈕,雖然,它拋出一個JavaScript錯誤(預期的對象)。 我也試過以下,但他們也拋出JavaScript錯誤(對象不支持此屬性)。

<input type="button" onclick="$.hellothere('hi');" value="jquery"/> 

<input type="button" onclick="$.fn.hellothere('hi');" value="jquery"/> 

我缺少什麼?

UPDATE:這是發生了什麼事,澄清小有一點。 我有一個按鈕:

<input type="button" class="mybutton" value="jquery"/> 

在頁面加載,我給你一個onclick事件到按鈕與$():

$(function(){ 
    $(".mybutton").click(function(){ 
    //Do some stuff 
    mybuttoncallback(dataprocessed); 

    }); 

    function senditoff(finaldata){ 
      //send the data off 
    } 
}); 

所以這個按鈕是一對夫婦的網頁,但確實不同處理數據的東西。所以,「mybuttoncallback」是本地的頁面本身,因爲不同的頁面可以不同方式處理數據的JavaScript方法。

function mybuttoncallback(thedata){ 
    //process the data 
    senditoff(hereitis); 
} 

的「senditoff」的方法是在jQuery代碼,因爲所有的頁面把它關閉的方法相同。 我不希望將任何東西移出$(),因爲許多頁面都必須更改。 ('senditoff'方法是上例中的'hellothere'方法。)

那麼javascript方法可以調用jquery的'senditoff'方法嗎?

回答

2

如果你真的需要擴展jQuery對象,試試這個:

<script language="javascript"> 
$.hellothere = function(strng){ alert(strng); } 
</script> 
<input type="button" onclick="$.hellothere('hi');" value="jquery"/> 
+0

輝煌!不過,我不必把它從$()中取出。這樣,它可以在$()中使用方法,並且仍然可以從$()之外調用。我修改了你的答案以反映這一點。謝謝! – ovaherenow 2011-04-26 22:14:21

+0

@overherenow不客氣。^_ ^ – 2011-04-26 22:21:06

0

試試這個。你不需要jQuery的任何特殊屬性來做到這一點。

<script language="javascript">   
    function hellothere(strng){ 
     alert(strng); 
    }  
</script> 
<input type="button" onclick="hellothere('hi');" value="jquery"/> 
+0

我寧願不要它,因爲「hellothere」調用jQuery的初始化中的其他方法遷出。 – ovaherenow 2011-04-26 21:49:27

0

移動這一功能出的document.ready,使其全球

你得到的,因爲範圍問題的錯誤。

function hellothere(strng){ 
       alert(strng); 
      } 
+0

我不想將它移出來,因爲'hellothere'在jQuery初始化中調用了其他方法。 – ovaherenow 2011-04-26 22:08:29