我想創建一個jQuery插件,並將其用於頁面中的某些HTML元素。 這是我的HTML代碼:爲某些HTML元素製作jquery插件
<select class="test">
<option>
111
</option>
<option>
222
</option>
<option>
333
</option>
</select>
<select class="test">
<option>
444
</option>
<option>
555
</option>
</select>
我想用我的插件select
元素。 這是我的插件樣本:
(function ($) {
$.fn.testplug = function() {
var res = "";
this.children("option").each(function(){
res+=$(this).text()+"#";
});
alert(res);
};
}(jQuery));
及其使用:
$(".test").testplug();
現在我的方面有兩個res
價值觀,其中之一應該是111#222#333#
和其他應444#555#
,但我有一個結果,它是111#222#333#444#555#
。 我該如何獲得我想要的結果? Link to jsfiddle
是的,它的工作,但我有超過2選擇元素,我也不想使用'更改'事件。 –
檢查更新@SamanGholami如果你想使用你的原始代碼,你可以這樣做 '$('。test')。each(function(){ $(this).testplug(); });' – Anton
是,這是正確的。坦克有很多:) –