我从这里的另一篇文章中找到了这个jfiddle。
原文:http://jsfiddle.net/ZTF5J/2/
使用1.9和我的更改:http://jsfiddle.net/4423c/
看起来Jquery 1.9不再支持.live()
。我设法修改了部分代码以删除下拉菜单,但添加新过滤器无法正常工作。
以下代码允许您一次删除过滤器。但是,添加新过滤器时,它不会检查当前是否存在值。
$('body').on('click', '.closeselect', function(){
if($('.closeselect').length > 1) {
$(this).parent().remove();
disableSelectedOption();
$('#addmore').show();
}
});
我尝试修改检查选择值的其他部分。显然它不能正常工作。
$('body').on('change', '.mySelect', function(){
disableSelectedOption();
});
答案 0 :(得分:3)
$(this).attr('disabled', 'disabled');
应该是
$(this).prop('disabled', 'disabled');
从jQuery 1.6开始,.attr()方法为属性返回undefined 尚未设定。 检索和更改DOM属性,例如
checked
,selected
或disabled
表单元素状态,请使用 .prop()方法。
答案 1 :(得分:0)
代码有一些问题,所以我重写了它here:
$(function() {
var $container = $('.js-selectblock'),
nrOfOptions = $container.find('select').prop('options').length,
$getBlocks = function() {
return $container.children('.js-select');
},
$getParent = function(element) {
return $(element).closest('.js-select');
};
$('#addmore').click(function() {
var $blocks = $getBlocks();
if ($blocks.length < nrOfOptions) {
// restrict values on new dropdown
var $new = $blocks.eq(0).clone();
restrictValues($new.find('select'), getSelectedValues(), true);
$new.appendTo($container);
updateButtons();
}
});
$container.on('click', '.closeselect', function() {
if ($getBlocks().length > 1) {
$getParent(this).remove();
updateButtons();
}
});
$container.on('change', '.mySelect', function() {
$getBlocks().not($getParent(this)).each(function() {
restrictValues($('select', this), getSelectedValues());
});
});
function restrictValues($element, values, isnew)
{
var options = $element.prop('options'),
selected = $element.prop('selectedIndex');
for (var i = 0; i < options.length; ++i) {
if (values.indexOf(options[i].value) !== -1) {
options[i].disabled = isnew || selected != i;
if (isnew && selected == i) {
++selected;
}
} else {
options[i].disabled = false;
}
}
$element.prop('selectedIndex', selected);
}
function getSelectedValues()
{
var values = [];
$getBlocks().find('select').each(function() {
values.push($(this).val());
});
return values;
}
function updateButtons()
{
$('#addmore')[$getBlocks().length < nrOfOptions ? 'show' : 'hide']();
}
});