【问题标题】:Append item in select2 on button click在按钮单击时在 select2 中附加项目
【发布时间】:2017-04-05 01:58:27
【问题描述】:

我在我的 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 模块使用它。

【问题讨论】:

    标签: javascript jquery drupal select2 jquery-select2-4


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      相关资源
      最近更新 更多