我正在尝试使用select2
文本选项将文本附加到freeform
中添加的任何新值。附加的文本我想在select元素上设置(在我的例子中是通过mvc帮助器)。
问题是进入templateResult的数据没有元素。在我搜索到的任何地方,data.element用于进入DOM,但它并不适合我,我不知道为什么。如果我查看createTag函数,params也没有元素。容器只是一个“li”,显然还没有在dom,没有孩子或父母。
这是代码:
$('.custom-dropdown').each(function() {
$(this).css('width', '100%');
if ($(this).hasClass('freeform')) {
$(this).select2({
tags: true,
createTag: function(params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function(data, container) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
//data.element is undefined here!!!
}
}
return $result;
},
placeholder: "Press ENTER for list of options",
allowClear: true,
selectOnClose: true
});
} else {
$(this).select2({
placeholder: "Press ENTER for list of options",
allowClear: true,
selectOnClose: true,
});
}
$(this).on('select2:select', function(e) {
if (e.params.data.text != '') {
var id = $(this).attr('id');
var select2 = $("span[aria-labelledby=select2-" + id + "-container]");
select2.removeAttr('style');
}
}); $(this).on('select2:close', function() {
$(this).focus();
});
});
选择的一个例子是:
选择class="custom-dropdown freeform"
data-appendme="blorg"
templateResult
用于创建dom。在创建之前,您无法访问dom。
也许你需要这样的东西:
(将“data-appendme”的值附加到createTag
中选项的文本中)
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<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>
</head>
<body>
<link rel="stylesheet" href="style.css">
<script src="index.js"></script>
<select class="custom-dropdown freeform" data-appendme="blorg"></select>
<script>
$('.custom-dropdown').each(function () {
var $select = $(this);
$select.css('width', '100%');
if ($select.hasClass('freeform')) {
$select.select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term + $select.data('appendme'),
newOption: true
}
},
templateResult: function (data, container) {
var $result = $("<span></span>");
$result.text(data.text);
return $result;
},
placeholder: "Press ENTER for list of options",
allowClear: true,
selectOnClose: true
});
} else {
$(this).select2({
placeholder: "Press ENTER for list of options",
allowClear: true,
selectOnClose: true,
});
}
$(this).on('select2:select', function (e) {
if (e.params.data.text != '') {
var id = $(this).attr('id');
var select2 = $("span[aria-labelledby=select2-" + id + "-container]");
select2.removeAttr('style');
}
});
$(this).on('select2:close', function () {
$(this).focus();
});
});
</script>
</body>
</html>
如果你不想在选项中使用“blorg”但是想在select标签中使用它,你可以用templateResult
中的空字符串替换它。