如何动态修改< select>在物化css框架中 [英] How to dynamically modify <select> in materialize css framework

查看:544
本文介绍了如何动态修改< select>在物化css框架中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用materialize css框架。现在,materialize将任何选择标记转换为ul和li元素的集合。以前,使用JQuery,我可以这样做:

I just started using the materialize css framework. Now, materialize converts any select tag into a collection of ul and li elements. Before, using JQuery, I was able to do this:

var $selectDropdown = $("#dropdownid");
$selectDropdown.empty();
$selectDropdown.html(' ');
var value = "some value";
$selectDropdown .append($("<option></option>").attr("value",value).text(value));

我的html只是一个示例选择标签:

My html is just a sample select tag:

之前,这是工作。现在它失败。使用javascript动态地重新填充此下拉列表的另一种方法是什么?

Before, this was working. Now it fails. What would be an alternative for repopulating this dropdown dynamically using javascript?

推荐答案

根据关于实现表单


此外,您需要单独调用任何动态生成的选择您的页面生成的元素

In addition, you will need a separate call for any dynamically generated select elements your page generates

所以最好的方法是重新绑定生成选择并额外调用 .material_select()

So the best way is to just re-bind the generated select with an additional call to .material_select().

为了重新可用性, a href =http://stackoverflow.com/a/2712188/1366033>元素已更改时监听器,然后在更新原始选择时触发该监听器

For re-usability, you can set up a listener when the elements have changed and then trigger that listener whenever you update the original select

// add new option
$selectDropdown.append($("<option></option>"));

// trigger event
$selectDropdown.trigger('contentChanged');

$('select').on('contentChanged', function() {
  // re-initialize (update)
  $(this).material_select();
});

这只需要更新已更改的特定select元素。

This has the benefit of only needing to update the particular select element that has changed.

$(document).ready(function() {

  // initialize
  $('select').material_select();

  
  $("#myButton").click(function() {
    
    // clear contents
    var $selectDropdown = 
      $("#dropdownid")
        .empty()
        .html(' ');

    // add new value
    var value = "some value";
    $selectDropdown.append(
      $("<option></option>")
        .attr("value",value)
        .text(value)
    );

    // trigger event
    $selectDropdown.trigger('contentChanged');
  });


  $('select').on('contentChanged', function() {
    // re-initialize (update)
    $(this).material_select();
  });
  
});

<link  href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/js/materialize.min.js"></script>

<a class="waves-effect waves-light btn" id="myButton">
  Change Dropdown
</a>

<select id="dropdownid" >
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>

这篇关于如何动态修改&lt; select&gt;在物化css框架中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆