[英]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.