我正在練習製作我自己的jquery插件。我可以製作簡單的插件,但現在我變得更加複雜。jQuery自定義插件語法
我想創建一個插件來偵聽表單的提交,並驗證所有的輸入。我知道那裏有幾個插件已經做了我想做的事情,但我現在有興趣自己學習它。
這裏是我的簡單形式:
<form id="testform">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="fname" id="fname" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" value="Validate" /></td>
</tr>
</table>
</form>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("#testform").validateMyForm();
});
</script>
對我來說,這是香草味到我的表單元素。我沒有添加任何類到輸入,而不是其他元數據。 但是,我打算使用不是典型的元數據,並且屬於我未來的表單驗證插件。
例子:
<input type="text" name="fname" id="fname" validate="min:2,max55,msg:Invalid First Name" />
當然,我敢肯定,驗證標籤將有更多的選擇。
這裏是我的插件開始:
(function($) {
$.fn.validateMyForm = function(options){
// settings defaults
var settings = $.extend({'addclasstoinput':''}, options);
return this.each(function(){
});
};
})(jQuery);
此處,我感到困惑。 這個插件意味着當提交按鈕被按下時,或者當提交表單時基本上是這樣做的。
我已經使用過這樣的代碼: $(「form.someform」)。submit(function(){/ * do whatever * /}); 所以我期待這是我需要做的插件。
這看起來對任何jquery插件退伍軍人都是正確的嗎?
(function($) {
$.fn.validateMyForm = function(options){
// settings defaults
var settings = $.extend({'addclasstoinput':''}, options);
var alertElements = '';
$(this).submit(function(){
$('input').attr("validate").each(function() {
// `this` is the div
alertElements += $(this).attr("validate");
alertElements += '\n';
});
alert(alertElements); // let's get a popup of the detected tags
});
};
})(jQuery);
到目前爲止,我在FF錯誤控制檯中收到「undefined alertElements」錯誤。 我也擔心我沒有正確使用插件內的$(this)。當我通過表單輸入循環時,我看到自己使用$(this)來捕獲任何「驗證」屬性。這是我應該如何編碼它?
$(this)不是div,因爲你正在調用attr()函數返回的字符串。 – 2012-03-18 21:08:11
你的插件看起來很悽慘:| 1.'this.'裏面的$ .fn.xxxx'已經是一個jQuery對象。 2.你的插件只允許使用一次。 'alertElements'永遠不會被重置爲一個空字符串(無論如何它應該在'submit'中聲明)。它採用文檔中的所有輸入元素,而不包括減少輸入元素集的選項。 - >你的插件不是很便攜。 – 2012-03-18 21:10:24