我正在尝试为一系列html选择输入开发一个JQuery插件。 如果任何选择更改,则将更改/重新加载所有后续选择。
这是html -
<select id="first" class="myselect" data-child ="second">...</select>
<select id="second" class="myselect" data-child ="third">..</select>
<select id="third" class="myselect" data-child ="fourth">...</select>
....
$('.myselect').MySelect();
这是我到目前为止的插件 -
(function ($) {
$.fn.MySelect= function () {
return this.each(function () {
var $This = $(this);
var childId = $This.attr('data-child');
$This.change(function (e) {
e.preventDefault();
if (childId !='none') {
var $Child = $('#' + childId);
$Child.Reset(); //Should be Recursive call
}
});
});
};
}(jQuery));
如何在插件中执行此操作?
答案 0 :(得分:0)
一种方法是使用一个自定义事件,当触发时执行您想要的任何重置,然后触发自身更改,使其沿着链条级联
(function($) {
$.fn.MySelect = function() {
return this.each(function() {
var $This = $(this);
var childId = $This.attr('data-child'),
$child = childId != 'none' ? $('#' + childId) : null;
$This.on('change', function(e) {
e.preventDefault();
$child && $child.trigger('my-reset')
}).on('my-reset', function(e) {
$This.val('').trigger('change');
});
});
};
})(jQuery);
$(function() {
$('.myselect').MySelect();
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first" class="myselect" data-child="second">
<option value=""></option>
<option value="1">One</option>
<option value="2"selected>Two</option>
</select>
<select id="second" class="myselect" data-child="third">
<option value=""></option>
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
<select id="third" class="myselect" data-child="fourth">
<option value=""></option>
<option value="1">One</option>
<option value="2" selected>Two</option>
</select>
<select id="fourth" class="myselect" data-child="none">
<option value=""></option>
<option value="1">One</option>
<option value="2" selected>Two</option>
</select>
&#13;