[英]How can I use this multiselect dropdown twice on one page so each instance outputs to its own array?
I want to place two separate multiselct dropdown menus on one page for a form I am designing. 我想在一个页面上放置两个单独的multiselct下拉菜单,用于我正在设计的表单。
I found this lovely dropdown with checkboxes that I would like to use: 我找到了这个可爱的下拉列表,我想使用复选框:
https://codepen.io/bseth99/pen/fboKH https://codepen.io/bseth99/pen/fboKH
I am trying to figure out the best way to run two instances of this dropdown on the same page, so that each dropdown's selections are saved in their own array. 我试图找出在同一页面上运行此下拉列表的两个实例的最佳方法,以便每个下拉列表的选择都保存在它们自己的数组中。
var options = [];
$( '.dropdown-menu a' ).on( 'click', function( event ) {
var $target = $( event.currentTarget ),
val = $target.attr( 'data-value' ),
$inp = $target.find( 'input' ),
idx;
if ( ( idx = options.indexOf( val ) ) > -1 ) {
options.splice( idx, 1 );
setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
} else {
options.push( val );
setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
}
$( event.target ).blur();
console.log( options );
return false;
});
Right now, if I place two instances of the button's HTML on my page, both dropdowns will modify the same "options" array because it's using a class selector for dropdown-menu. 现在,如果我在页面上放置按钮HTML的两个实例,则两个下拉列表都将修改相同的“options”数组,因为它使用了一个类选择器来显示下拉菜单。 I know I can use an ID selector instead of a class selector, and then just use the same block of jQuery over again with a different array, but is that really the best way to do this?
我知道我可以使用ID选择器而不是类选择器,然后使用不同的数组再次使用相同的jQuery块,但这真的是最好的方法吗? I am new to jQuery but that seems bloated.
我是jQuery的新手但看起来很臃肿。
$( '.dropdown-menu a' ).on( 'click', function( event ) {
var $target = $( this ),
val = $target.data( 'value' ),
$inp = $target.find( 'input' ),
idx;
var options = $target.closest('.dropdown-menu').data('options') || [];
if ( ( idx = options.indexOf( val ) ) > -1 ) {
options.splice( idx, 1 );
setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
} else {
options.push( val );
setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
}
$target.closest('.dropdown-menu').data('options', options);
$( event.target ).blur();
return false;
});
console.log($( '.dropdown-menu:eq(0)' ).data('options'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.