我通过这个例子使用meteor来选择: meteor is not working with selectize.js
Template.hello.onRendered(function(){
$('#select-links').selectize({
maxItems: null,
valueField: 'id',
searchField: 'title',
options: [
{id: 1, title: 'DIY', url: 'https://diy.org'},
{id: 2, title: 'Google', url: 'http://google.com'},
{id: 3, title: 'Yahoo', url: 'http://yahoo.com'},
],
render: {
option: function(data, escape) {
return '<div class="option">' +
'<span class="title">' + escape(data.title) + '</span>' +
'<span class="url">' + escape(data.url) + '</span>' +
'</div>';
},
item: function(data, escape) {
return '<div class="item"><a href="' + escape(data.url) + '">' + escape(data.title) + '</a></div>';
}
},
create: function(input) {
return {
id: 0,
title: input,
url: '#'
};
}
});
});
<!-- html -->
<template name="hello">
<select id="select-links" placeholder="Pick some links..."></select>
</template>
所以在onChange事件上我想得到
保存到数据库的该值的值和ID
。
结果可能是这样的:{id:1,text:google}
那我怎么能这样做?
来自流星的新人答案 0 :(得分:1)
您可以利用开箱即用支持的onChange
回调。这是一个有效的例子。
import { Template } from 'meteor/templating';
import { $ } from 'meteor/jquery';
import { _ } from 'meteor/underscore';
import selectize from 'selectize';
import './main.html';
import 'selectize/dist/css/selectize.css';
const selectLinks = [
{ id: 1, title: 'DIY', url: 'https://diy.org' },
{ id: 2, title: 'Google', url: 'http://google.com' },
{ id: 3, title: 'Yahoo', url: 'http://yahoo.com' },
];
const getLinkTitle = (id) => {
let title;
if (id) {
const selectedLink = _.find(selectLinks, (link) => {
return link.id === parseInt(id);
});
if (selectedLink) {
title = selectedLink.title;
}
}
return title;
};
Template.body.onRendered(function onRendered() {
$('#select-links').selectize({
maxItems: null,
valueField: 'id',
searchField: 'title',
options: selectLinks,
render: {
option: function(data, escape) {
return '<div class="option">' +
'<span class="title">' + escape(data.title) + '</span>' +
'<span class="url">' + escape(data.url) + '</span>' +
'</div>';
},
item: function(data, escape) {
return '<div class="item"><a href="' + escape(data.url) + '">' + escape(data.title) + '</a></div>';
}
},
create: function(input) {
return {
id: 0,
title: input,
url: '#'
};
},
onChange: function (values) {
if (values) {
values.forEach((value) => {
// Can save to your collection/database here; for now
// just logging in the format you requested.
console.log({
id: value,
text: getLinkTitle(value)
});
});
}
}
});
});
答案 1 :(得分:0)
请注意这一点:
const getLinkTitle = (id) => { let title; if (id) { const selectedLink = _.find(selectLinks, (link) => { `return link.id === parseInt(id);` }); if (selectedLink) { title = selectedLink.title; } } return title; };
`return link.id === parseInt(id);`
注意那行代码。这取决于你的身份。我正在使用mongoDB,因此在我的实际应用程序中它不再是一个数字。