//左侧模板类目
var itemTmpl = `<div class="menu-item">
<img class="img" src="$picture" />
<div class="menu-item-right">
<p class="item-title">$name</p>
<p class="item-description">$description</p>
<p class="item-zan">$praise_content</p>
<p class="item-price">¥$min_price<span class="unit">/$unit</span></p>
</div>
<div class="select-content">
<div class="minus"></div>
<div class="count">$chooseCount</div>
<div class="plus"></div>
</div>
</div>`
//这里因为外面穿入了data,我们就不自己get了
function getList(data){
var list =data;
initRightList(list);
}
//渲染列表 parma array
function initRightList(list){
$('.right-list-inner').html('');
list.forEach((item, index) => {
if(!item.chooseCount){
item.chooseCount = 0;
}
var str = itemTmpl.replace('$picture', item.picture)
.replace('$name', item.name)
.replace('$description', item.description)
.replace('$praise_content', item.praise_content)
.replace('$min_price', item.min_price)
.replace('$unit', item.unit)
.replace('$chooseCount', item.chooseCount);
var $target = $(str);
$target.data('itemData', item);
$('.right-list-inner').append($target);
});
}
//渲染title parma array
function initRightTitle(str){
$('.right-title').text(str);
}
//增加右边点击事件
function addClick(){
$('.menu-item').on('click', '.plus', (e) =>{
var $count = $(e.currentTarget).parent().find('.count');
console.log('$count,我就是div.count', $count);
$count.text(parseInt($count.text()||'0')+1);
var $item = $(e.currentTarget).parents('.menu-item').first();
console.log('我是$(e.currentTarget).parents(.menu-item)',$(e.currentTarget).parents('.menu-item'));
console.log('我是$(e.currentTarget).parents(.menu-item).first()',$(e.currentTarget).parents('.menu-item').first());
// $(e.currentTarget).parents('.menu-item').first().css('background-color', 'red');
var $item1 = $(e.currentTarget).parents('.menu-item');
var itemData = $item.data('itemData');
itemData.chooseCount = itemData.chooseCount + 1;
});
$('.menu-item').on('click', '.minus', (e) =>{
var $count = $(e.currentTarget).parent().find('.count');
if($count.text() == 0) return;
$count.text(parseInt($count.text()||'0')-1);
var $item = $(e.currentTarget).parents('.menu-item').first();
var itemData = $item.data('itemData');
itemData.chooseCount = itemData.chooseCount - 1;
});
}
function init(data){ //这里的data指的是food_spu_tags,也就是list
getList(data.spus || []);
initRightTitle(data.name || '');
addClick();
}
//不能直接用init()的原因是,如果用了就会直接调用,但此时init的data还没传入
window.Right = {
refresh: init
}
难点addClick事件
var $count = $(e.currentTarget).parent().find(’.count’);
先上走一步,然后找到.count的div
c
o
u
n
t
.
t
e
x
t
(
p
a
r
s
e
I
n
t
(
count.text(parseInt(
count.text(parseInt(count.text()||‘0’)+1);
将其本身一开始的字符串转化为int
var $item = $(e.currentTarget).parents(’.menu-item’).first();
一直往上搜寻找到当前.menu-item
这里加不加.first()都可以,我也要问人其不同
var itemData = $item.data(‘itemData’);
每个.menu-item本身就带有data,因为上面有
var $target = $(str);
$target.data(‘itemData’, item);
每个.menu-item都在遍历里被注入了数据