Javascript 每一个都用下划线表示
我试图在集合中找到一个属性等于html选择选项值的模型Javascript 每一个都用下划线表示,javascript,jquery,backbone.js,underscore.js,Javascript,Jquery,Backbone.js,Underscore.js,我试图在集合中找到一个属性等于html选择选项值的模型 <div id="hospital-details"> <select name="hospitalnames"> <option><%- model.get('name') %></option> </select> </div> 找到带有属性的locationModel后,我无法退出循环。有什么帮助吗?现在我已经调查过了
<div id="hospital-details">
<select name="hospitalnames">
<option><%- model.get('name') %></option>
</select>
</div>
找到带有属性的locationModel后,我无法退出循环。有什么帮助吗?现在我已经调查过了
但是没有成功。试试这个
var name = $(this).val();
var flag=true;
locationListCollection.each(function(locationModel) {
if (flag && $.trim(locationModel.get('name')) == $.trim(name)) {
that.locationModel = locationModel;
flag=false;
//return false;// to break the $.each loop
}
});
你总是可以去旧学校
$('select[name="hospitalnames"]').change(function() {
var name = $(this).val();
for (var i = 0; i < locationListCollection.length; ++i) {
var locationModel = locationListCollection.models[i];
if ($.trim(locationModel.get('name')) == $.trim(name)) {
that.locationModel = locationModel;
break;
}
}
});
$('select[name=“hospitalnames”]”)。更改(函数(){
var name=$(this.val();
对于(变量i=0;i
如果搜索第一个匹配项,则使用的方法错误。收藏有很多,特别是它们混合了:
查找查找(列表、迭代器、[context])
查看列表中的每个值,返回第一个通过真值测试的值(迭代器),或者如果没有值通过测试,则返回未定义的值
大概是这样的:
var name = $.trim($(this).val());
that.locationModel = locationListCollection.find(function(locationModel) {
return $.trim(locationModel.get('name')) == name;
});
var name = $.trim($(this).val());
that.locationModel = locationListCollection.findWhere({ name: name });
如果模型中的名称
s经过预修剪且美观干净,则可以使用:
findWhere集合。findWhere(属性)
与where类似,但直接返回集合中与传递的属性匹配的第一个模型
像这样:
var name = $.trim($(this).val());
that.locationModel = locationListCollection.find(function(locationModel) {
return $.trim(locationModel.get('name')) == name;
});
var name = $.trim($(this).val());
that.locationModel = locationListCollection.findWhere({ name: name });
顺便说一句,这是:
console.log(locationModel);
不会给你任何东西,因为locationModel
和那是不同的东西。locationModel
是不同的东西。简短的是否定的
如果您查看一下下划线的源代码,就会发现它们使用了一个breaker对象来快速停止.each(),但该对象仅在内部可用
我不建议这样做,但您可以始终修改源以公开此断路器对象(请参见注释源中的基线设置)
)。然后您将只返回此对象,而不是返回false。但您可能需要删除本机forEach调用以保持行为一致。所以这不值得
_.each(function(arr) {
if(condition) {
return _.breaker; // Assuming you changed the source.
}
});
由于搜索的是单个项目而不是.each(),请使用:
我正在LocationListCollection中搜索locationModel,在这种情况下,arr将是LocationListCollection?我希望将代码仅限于库方法。很好+1.