我正在尝试在集合中查找属性等于 html 选择选项值的模型。
<div id="hospital-details">
<select name="hospitalnames">
<option><%- model.get('name') %></option>
</select>
</div>
每当医院名称更改时,都会触发jquery更改回调以查找具有所选选项值作为属性值的locationModel,如下所示,
$('select[name="hospitalnames"]').change(function() {
var name = $(this).val();
locationListCollection.each(function(locationModel) {
if ($.trim(locationModel.get('name')) == $.trim(name)) {
that.locationModel = locationModel;
return false; // control is returned to underscore.min.js
}
});
});
console.log(that.locationModel); // this is not being displayed at all
找到具有属性的locationModel后,我无法退出循环。有什么帮助吗?此时此刻我已经研究过 this但没有成功。
最佳答案
如果您正在搜索第一个匹配项,那么您使用了错误的方法。收藏有很多Underscore methods mixed in ,特别是他们有 find
混合在:
find
_.find(list, iterator, [context])
Looks through each value in the list, returning the first one that passes a truth test (iterator), or
undefined
if no value passes the test.
类似这样的事情:
var name = $.trim($(this).val());
that.locationModel = locationListCollection.find(function(locationModel) {
return $.trim(locationModel.get('name')) == name;
});
如果模型中的名称
已预先 trim 且漂亮且干净,那么您可以使用 findWhere
:
findWhere
collection.findWhere(attributes)
Just like where, but directly returns only the first model in the collection that matches the passed attributes.
像这样:
var name = $.trim($(this).val());
that.locationModel = locationListCollection.findWhere({ name: name });
<小时/>
顺便说一句,这个:
console.log(locationModel);
不会给你任何东西,因为 locationModel
和 that.locationModel
是不同的东西。
关于javascript - 每个都打破下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19263375/