2012-10-22 60 views
1

不知道我在做什麼不正確。我在我的自定義jQuery插件中有一個函數,我的瀏覽器告訴我它是未定義的。jQuery自定義插件undefined js函數

任何人都可以看到我做了什麼錯內部:

(function($){ 

    $.fn.myCustomPlugin = function() { 

    return this.each(function() { 

     var theValue = $(this).text().trim().replace(/ /g,''); 

     // STOP if theValue return nothing 
     if (theValue === null || theValue === undefined || theValue == ""){ 
      $(this).html("nothing inside the span"); 
      return true; 
     } 


     function clickActions() 
     { 
      alert("This alert shows when clicking on the element");  
      return false; 
     } 


     $(this).html('<a href="javascript:void(0);" onClick="clickActions()">'+theValue+'</a>'); 

    }); // eof .each 


    }; 
})(jQuery); 

的HTML是簡單的電話號碼裏面涵蓋:

<span class="formatme">123-8749674</span><br /> 
<span class="formatme">123-8749674</span><br /> 
<span class="formatme">123-8749674</span><br /> 
<span class="formatme">123-8749674</span><br /> 
<span class="formatme">123-8749674</span><br /> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.formatme').myCustomPlugin(); 
}); 
</script> 

功能clickActions()在錯誤的地方可能是簡單地,但是我已經將它移到了插件代碼中,結果相同。

+0

究竟是什麼錯誤? – Madbreaks

+0

檢查我的答案。 –

回答

0

您可以簡單地使用

$(this).text(theValue).on('click', function(e){ 
    alert("This alert shows when clicking on the element");  
    return false; 
}); 

也是繼線

var theValue = $(this).text().trim().replace(/ /g,''); 

應該$.trim()

var theValue = $.trim($(this).text()).replace(/ /g,''); 

Working Example Here

+0

感謝您添加$ .trim()註釋。修復了IE問題 – coffeemonitor

+0

歡迎您:-) –

0

你需要聲明你正是如此運作:

window.clickActions = function(){ 
    alert("This alert shows when clicking on the element");  
    return false; 
} 

...如果它有全局作用域,你現在正在試圖訪問它,在onclick處理。

這就是說,我建議提供一個對象並在該對象範圍內進行作用域以防止污染全局名稱空間,這是最佳實踐。

乾杯

+0

這似乎適用於FF和Chrome。 IE似乎有問題。 – coffeemonitor