javascript - 每个都打破下划线

标签 javascript jquery backbone.js underscore.js

我正在尝试在集合中查找属性等于 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);

不会给你任何东西,因为 locationModelthat.locationModel 是不同的东西。

关于javascript - 每个都打破下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19263375/

相关文章:

javascript - 如何使用 JavaScript 在 HTML 数据表中可视化 MySQL 表中超过 1000 行的数据?

jquery - 使用 jQuery 更改 ajax 呈现控件的样式

backbone.js - 在方法中从 Backbone.Model 获取默认值?

javascript - JavaScript 中这种情况的首选模式是什么?

javascript - 创建表时 marionette.js 中的嵌套 View

javascript - Angular:检测整个应用程序中的用户点击

鼠标悬停时不显示 JavaScript 元素

jquery - 使用 Django + Jquery 聊天弹出窗口

javascript - 命名数组和索引数组之间的区别 - javascript

javascript - 搜索在数据表中不起作用 - Jquery