这是我的代码:
if ($(this.el).find('.select-picture').is(':checked')) {
var source = $(this).parent().prev().attr('src');
document.cookie = "imagePath=" + source;
var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)imagePath\s*\=\s*([^;]*).*$)|^.*$/, "$1");
console.log(myCookie);
}
我有一个 .select-picture 类,我正在寻找它的父元素的前一个元素,并且我想对其执行操作(将图像路径保存到 cookie)。当将代码放在 html 文档中的标签之间时,代码可以很好地工作,但是当将其放在 Backbone 的 View 中时,控制台会返回“未定义”。
我几乎可以肯定这是因为 Backbone 中的“this”与之前位置的“this”不同,但我不知道如何更改它以使其正常工作。
有人可以帮助我吗?
编辑 - 这是 HTML:
<div class="img-holder">
<img src="images/picture.jpg" class="img-responsive top-img choose-img"/>
<form>
<input type="radio" name="vehicle" value="Bike" class="select-picture">
</form>
</div>
<div class="img-holder">
<img src="images/picture2.jpg" class="img-responsive choose-img"/>
<form>
<input type="radio" name="vehicle" value="Bike" class="select-picture">
</form>
</div>
最佳答案
理解 JavaScript 中的范围和上下文非常重要。 我想你的模板是这样的:
<script id="template_id" type="text/template">
<div>
<% _.each(images, function(image){ %>
<div class="row">
<img src="<%= image.src %>" />
<div class="form-group">
<input class="select-picture" name="image[<%= image.uid %>]['is_checked']" type="checkbox" />
<input name="image[<%= image.uid %>]['quantity']" type="text" />
</div>
<div>
<% }); %>
</div>
</script>
在主干 View 中,您可以执行类似的操作:
Backbone.View.extend({
el : $('#template_id'),
function onChecked(){
/*
* this.$el refer to #template_id element.
*/
this.$el.find('.select-picture:checked').each(function(index){
/*
* Now this referer to the current context.
*/
var source = $(this).parent().prev().attr('src');
document.cookie = "imagePath=" + source;
var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)imagePath\s*\=\s*([^;]*).*$)|^.*$/, "$1");
console.log(myCookie);
})
},
});
看一下:
关于javascript - 在 Backbone.js 中使用什么来代替 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25421683/