同样,我们通过函数的方式将运动类型插入我们的HTML代码中
_renderWorkout ( workout ) { let html = ` <li class="workout workout- ${ workout. type} " data-id=" ${ workout. id} "><h2 class="workout__title"> ${ workout. description} </h2><div class="workout__details"><span class="workout__icon"> ${ workout. type === 'running' ? '🏃♂️' : '🚴♀️' } </span><span class="workout__value"> ${ workout. distance} </span><span class="workout__unit">km</span></div><div class="workout__details"><span class="workout__icon">⏱</span><span class="workout__value"> ${ workout. duration} </span><span class="workout__unit">min</span></div> ` ; if ( workout. type === 'running' ) html += ` <li><div class="workout__details"><span class="workout__icon">⚡️</span><span class="workout__value"> ${ Workout. pace. toFixed ( 1 ) } </span><span class="workout__unit">min/km</span></div><div class="workout__details"><span class="workout__icon">🦶🏼</span><span class="workout__value"> ${ workout. cadence} </span><span class="workout__unit">spm</span></div> ` ; if ( workout. type === 'cycling' ) html += ` <div class="workout__details"><span class="workout__icon">⚡️</span><span class="workout__value"> ${ Workout. speed. toFixed ( 1 ) } </span><span class="workout__unit">min/km</span></div><div class="workout__details"><span class="workout__icon">🦶🏼</span><span class="workout__value"> ${ workout. elevationGain} </span><span class="workout__unit">spm</span></div></li> ` ; }
}
这里主要注意我们需要把相同的部分和不通的部分分开这么写就行了,然后把数据变化的地方用模板自变量的方式来写入即可,非常简单,就废话不多说了,这里有个月份的读取,上面的代码需要修改一下来让我们读取到现在的月份和日
_setDescription ( ) { const months = [ 'January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October' , 'November' , 'December' ] ; this . description = ` ${ this . type[ 0 ] . toUpperCase ( ) } ${ this . type. slice ( 1 ) } on ${ months[ this . date. getMonth ( ) ] } ${ this . date. getDate ( ) } ` ; }
现在我们HTML的模板已经做好,现在我们只需要知道我们如何或者说在哪里去插入我们的html就可以了
form. insertAdjacentHTML ( 'afterend' , html) ;
这样就将表单完全的展现出来了 然后,不要忘记,每次输入时候隐藏表单,并清空上一次输入内容,方便我们的下一次输入
this . _hideForm ( ) ; _hideForm ( ) { inputDistance. value = inputDuration. value = inputCadence. value = inputElevation. value = '' ; form. style. display = 'none' ; form. classList. add ( 'hidden' ) ; setTimeout ( ( ) => ( form. style. display = 'grid' ) , 1000 ) ; }