gpt4 book ai didi

javascript - 缺少上下文 JavaScript

转载 作者:行者123 更新时间:2023-11-28 19:11:36 24 4
gpt4 key购买 nike

我有一个方法_addEvents,它使用JQuery on. 函数设置按钮的单击事件。这也给出了 cartCollection.removeItem(buttonId); 的单击按钮的 id 问题是它不断丢失按钮的 id 值并给出 undefined

已编辑
_addEvents 必须从此模板获取单击按钮的 ID:

<script type="text/template" id="cartTemplate">
<ul id = "cartList" >
<% for(var i = 0; i < data.items.length; i++){%>
<%if(data.items[i].quantity === 1){%>
<li><%=data.items[i].item.id%><br>
<%=data.items[i].item.name%><br>
Price per Phone:<%=data.items[i].item.price%><br>
<%=data.items[i].thisItemTotal %><br>
Total Quantity:<%=data.TotalQuantity%><br>
Total Price:<%=data.total%><br>
<button id="<%=data.items[i].item.id%>" type="button" class="removeButton btn btn-default" aria-label="center-align">
Remove
</button>
</li>
<%} else {%>
<li><%=data.items[i].item.id%><br>
<%=data.items[i].item.name%><br>
Quantity:<%=data.items[i].quantity%><br>
Price per Phone:<%=data.items[i].item.price%><br>
<%=data.items[i].thisItemTotal %><br>
Total Quantity:<%=data.TotalQuantity%><br>
Total Price:<%=data.total%><br>
<button id="<%=data.items[i].item.id%>" type="button" class="removeButton btn btn-default" aria-label="center-align">
Remove
</button>
</li>
<%}%>
<%}%>
</ul>
</script>

_addEvents的实现以及该方法所属的对象:

var cartList = {
_itemsCollections: cartCollection,
_template: _.template($('#cartTemplate').html()),
_rootElement: $('#ordersCartDiv'),
//_rootElementUl: $("#cartList"),
initialize: function () {
'use strict';
//this.divId = divId;
//this._rootElementUl = $("#cartList");
//this._itemsCollections= cartCollection;
//bind(this._addEvents(),cartList);
this._addEvents();
},
render: function () {
'use strict';
var data = {
items: this._itemsCollections.getItems(),
total: this._itemsCollections.getTotalPrice(),
TotalQuantity: this._itemsCollections.getTotalQuantity()
};
var rendTemplate = this._template({data: data});
this._rootElement.html(rendTemplate);
this._addEvents();
console.log(this._itemsCollections);
},
_addEvents: function () {
'use strict';
var self = this;
this._rootElement.on('click','.removeButton' , function () {
var buttonId = $(self).attr('id'); // undefined
console.log('id:' + buttonId);
cartCollection.removeItem(buttonId);
cartList.render();
});
}
};


最佳答案

好的 - 您的 this 引用回调上下文,您应该从事件对象中获取单击的对象:

_addEvents: function () {
'use strict';
this._rootElement.on('click','.removeButton' , function ( e ) {
var buttonId = $( e.currentTarget ).attr('id'); // GET TARGET FROM EVENT
console.log('id:' + buttonId);
cartCollection.removeItem(buttonId);
cartList.render();
});
}

关于javascript - 缺少上下文 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com