我刚学习JavaScript并试验其标记的模板文字。
<p> Handlebars? Tagged template literals? <span> That is a question. </span> </p>
以上是HTML代码。我想用下面的代码实现类似的结果,但允许能够将变量str
和quote
替换为数组。
str = 'Handlebars? Tagged template literals?'
quote = 'That is a question.'
const renderMe = htmlString
`<p>
${str}
<span>
${quote}
</span>
</p>`
function htmlString(string, ...exp1) {
return () => {
const p = document.createElement("p")
p.textContent = exp1[0]
const span = document.createElement("span")
span.textContent = exp1[1]
return p //but how about span???
}
}
document.body.appendChild(renderMe())
正如你所看到的,我陷入了回归阶段。那么可以采取哪些措施来改进代码?
答案 0 :(得分:1)
您只需将p
追加到function htmlString(string, ...exp1) {
return () => {
const p = document.createElement("p")
p.textContent = exp1[0]
const span = document.createElement("span")
span.textContent = exp1[1]
p.appendChild(span)
return p
}
}
, 后设置内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbarSize="0dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<LinearLayout
android:padding="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Breakfast" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lunch" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:id="@+id/linearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dinner"
android:id="@+id/textView2" />
</LinearLayout>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
希望这会有所帮助:)