繁体   English   中英

如何更改select2中的占位符?

[英]How to change placeholder in select2?

如何使用 select2 更改数据占位符?

到目前为止,我已经尝试过这个。

$("#city").select2({placeholder:"foo"});

而这...

$("#city").attr("data-placeholder","bar");

但两者都不起作用。

我发现如果我只是设置 attr 例如$("#city").attr('data-placeholder', 'bar') ,则没有效果。 但是,如果我设置 attr 然后不带参数调用$("#city").select2() ,则占位符会更新。

例如

$("#city").attr("data-placeholder","bar");
$("#city").select2();

对于其他正在寻找属性解决方案以避免更改 JS 代码的人。 我只需要自己查找一个项目,似乎 select2 只需要属性 data-placeholder=""。

<select id="city" data-placeholder="my placeholder"></select>

在此处查看更多信息: select2 选项参考

您也可以在模板 (html) 级别这样做。 请务必在您的第一个标签上分配一个空白(例如“”)字符串。

<select id="city" data-placeholder="Select Anything">
  <option value=""></option>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

或者我们可以简单地通过javascript为占位符添加一个数据属性,它应该在select2初始化之前发生。

$('#city').data('placeholder','This is a placeholder');

演示

更直接的方法..

$('#select2-' + $id + '-container').find('.select2-selection__placeholder').text('Your Text');

其中$id是 select 元素的id

更多的hack-y解决方案,但不涉及重新启动整个select元素的解决方案是添加以下扩展:

$.fn.getSelect2Placeholder = function () {
    var $select2Container = $(this).data('select2').$container;
    return $select2Container.find('.select2-selection__placeholder').text();
};
$.fn.setSelect2Placeholder = function (placeholder) {
    var $select2Container = $(this).data('select2').$container;
    return $select2Container.find('.select2-selection__placeholder').text(placeholder);
};

这允许通过简单地编写来更新占位符:

$('#the-id-of-your-select2-element').setSelect2Placeholder("Your placeholder text.");

来源

把它放在你的定位器使用的 html 中,如下所示:

<select id="city" placeholder="my placeholder"></select>

对于 select2 版本 4,我在 js init 代码中指定了占位符文本,然后使用$select.select2{placeholder:"updated text..."}更新它

可以使用以下脚本:

$("#city").attr('placeholder', 'your text here' );

暂无
暂无

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

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