简体   繁体   English

bootstrap 4 selectpicker如何动态添加“子文本”

[英]bootstrap 4 selectpicker how to add 'subtext' dynamically

Working with Bootstrap-4 I'm trying to dynamically add 'data-subtext' next to all the option texts of a selectpicker. 使用Bootstrap-4,我试图在selectpicker的所有选项文本旁边动态添加“ data-subtext”。 Using the below code is ok with creating the list of options out of the array. 在数组外创建选项列表可以使用以下代码。 But I failed to find how to add the data-subtext text as well. 但是我也找不到如何添加数据子文本的方法。 Here is the relevant code: 以下是相关代码:

    <!---HTML part,use function to insert list of options  ------>      
                 <div class="form-group mr-2">        
                    <div class="col-mr-2">
                        <div class="input-group">
                            <div class="input-group-append">
                        <select class="selectpicker w-100"  data-show-subtext="true"  data-live-search="true" id="buttNameSel" name="buttNameF" onChange="replacButtName()">                
                              <option data-subtext="mysubtext_list" >select-from:</option>                          
   <!------   autofill the options---------->   
                      </select>
                            </div>
                        </div>
                    </div>
                 </div>
                <script type="text/javascript" > 
                // set option list of names
                selButtname = document.getElementById( 'buttNameSel' );
                var opt;
                for (i=0; i < nItems;i++) {
                   buttName = ButtNamesSplitList[i];
                   opt = document.createElement("option"); 
                   opt.text=buttName ;
                   selButtname.add(opt);    
                    }
                    $('.selectpicker').selectpicker('refresh');
                </script> 

You an update your code to add the attribute like this: 您更新代码以添加如下属性:

  <script type="text/javascript" > 
                // set option list of names
                selButtname = document.getElementById( 'buttNameSel' );
                var opt;
                for (i=0; i < nItems;i++) {
                   buttName = ButtNamesSplitList[i];
                   opt = document.createElement("option"); 
                   opt.text=buttName ;
                   opt.setAttribute("data-subtext", "your_sub_text"); //add subtext here
                   selButtname.add(opt);    
                    }
                    $('.selectpicker').selectpicker('refresh');
 </script> 

You can find more information how setAttribute works from this documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute 您可以从以下文档中找到有关setAttribute如何工作的更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/API/Element/setAttribute

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

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