繁体   English   中英

单击按钮将其添加到select2中

[英]Append item in select2 on button click

我在Drupal YAML表单中使用的是select2标记样式,因此用户可以查找并添加一些项目。

我在同一页面上所有带有图像和标题的项目,并且在每个图像旁边都有按钮。 我想让用户单击按钮并在select2中添加该项目(就像select2下拉列表一样)。

我尝试过这样的事情:

$('a.rentiraj').click(function (e) {
                e.preventDefault();
                // Get title
                var masina = $(this).closest('.views-row').find('.views-field-title span').text();
                // Result to add in select2 ul
                var result = '<li class="select2-selection__choice" title="' + masina + '"><span class="select2-selection__choice__remove" role="presentation">×</span>' + masina + '</li>';
                // Add result in select2 ul before last li
                $('.select2-selection ul li:last-child').before(result);
            });

但是没有成功。 当我单击按钮时添加了项目,但是当我单击select2中的项目旁边的“ X”时,如果我从select2下拉列表中添加项目,则所有项目都将消失,并且从select2下拉列表中仅添加了项目,因此无法删除它。

有人可以指出我正确的方向吗? 当我单击按钮时,如何在select2中而不是从下拉列表中而是从此列表外部添加新项?

这是我第一次使用select2。 我通过YAML Form Drupal 8模块使用它。

使用jquery中的ON代替click方法:

$('a.rentiraj').on('click', function (e) {

文档: http : //api.jquery.com/on/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM