大佬教程收集整理的这篇文章主要介绍了jquery – Select2:预选项目并通过templateSelection正确呈现,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这个问题是当你定义了一个templateSELEction时,它不仅返回所选值的文本,还返回一个完整的HTML DOM(例如,你可以应用样式,添加图像,图标等等,并将其作为渲染选择返回) .
templateSELEction接受输入,因为它来自数组数据源或ajax数据源等.每个项目代表一个选项,但它可能不仅仅是id和id和文本. templateSELEction可以考虑项目的许多属性来生成渲染输出.
您只能在< option>中定义值和文本.元件.您无法定义要设置为选定的实际对象(项),以便templateSELEction可以生成正确的输出.
定义templateSELEction时,定义一个将选项作为参数的函数,这样您就可以访问文本和选项的id作为可用变量.此函数将返回根据您的模板构建的对象.
看这个例子:
$(document).ready(function() { $('.js-example-basic-single').SELEct2({ width: 'width: 100%',templateSELEction: formatState }); }); $('.js-example-basic-single').val('WY'); $('.js-example-basic-single').trigger('change'); function formatState(statE) { console.log(statE); var $state = $( '<span>Content from the template: ' + state.element.text + ' ' + state.element.value + '</span>' ); return $state; }
<script src="https://code.jquery.com/jquery-2.2.4.js"></script> <link href="https://cdnjs.cloudFlare.com/ajax/libs/SELEct2/4.0.6-rc.0/css/SELEct2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudFlare.com/ajax/libs/SELEct2/4.0.6-rc.0/js/SELEct2.min.js"></script> <SELEct class="js-example-basic-single" name="state"> <option value="AL">Alabama</option> <option value="WY">Wyoming</option> </SELEct>
编辑:
由于您可以访问该状态,因此您可以访问使用动态数据定义的任何属性.并且您可以访问该元素,因此您也可以拥有数据属性.这使您可以做更精细的事情:
$(document).ready(function() { $('.js-example-basic-single').SELEct2({ width: 'width: 100%',templateSELEction: formatState,data: [{ id: 0,text: "Wyoming" },{ id: 1,text: "Alabama",SELEcted: true,disabled: true,},{ id: 2,text: "Washington",customProp: 'something' }] }); }); function formatState(statE) { console.log(statE); var $state if (state.customProp) { $state = $( '<span>Content from the template: ' + state.element.text + ' ' + state.element.value + ' and my custom property is <strong>' + state.customProp + '</strong></span>' ); } else { $state = $( '<span>Content from the template: ' + state.element.text + ' ' + state.element.value + '</span>' ); } return $state; }
<script src="https://code.jquery.com/jquery-2.2.4.js"></script> <link href="https://cdnjs.cloudFlare.com/ajax/libs/SELEct2/4.0.6-rc.0/css/SELEct2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudFlare.com/ajax/libs/SELEct2/4.0.6-rc.0/js/SELEct2.min.js"></script> <SELEct class="js-example-basic-single" name="state"> </SELEct>
以上是大佬教程为你收集整理的jquery – Select2:预选项目并通过templateSelection正确呈现全部内容,希望文章能够帮你解决jquery – Select2:预选项目并通过templateSelection正确呈现所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。