我想创建一个jquery插件,并将其用于我页面中的一些HTML元素。 这是我的HTML代码:
<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
答案 0 :(得分:1)
您正在选择这两个,因此您必须指定要使用的那个
$('.test:first').testplug() //111#222#333
和
$('.test:last').testplug() //444#555#
或
$('select').on('change',function(){
$(this).testplug();
});
或者你可以像这样循环遍历每个.test
$('.test').each(function(){
$(this).testplug();
});
你也可以像这样重写代码,循环遍历列表,然后在每个列表的末尾循环播放
(function ( $ ) {
$.fn.testplug = function() {
this.each(function(){
var res = "";
$(this).children('option').each(function(){
res+=$(this).text()+"#";
});
alert(res);
});
};
}( jQuery ));
答案 1 :(得分:1)
你的意思是一个叫做插件功能的2个警报?
$.fn.testplug = function() {
$(this).each(function(){
var res = "";
$(this).children("option").each(function(){
res+=$(this).text()+"#";
});
alert(res);
});
};