我想在 <div id = "newBook"></div> .
中显示具有 newBook 属性的元素(书)它是 webpack 项目。如果我需要一些额外的导入或类似的东西,请告诉我。
export class Book {
constructor(price, title, image, description) {
var bookTemplate = '<div class="col-lg-3 col-md-6 mb-4">\
<div class="card">\
<a href="#"><img class="mx-auto-d-block-card-img-top-fixed-top" src="{image}" width="335" height="340"\
alt=""></a>\
<div class="card-body">\
<h4>{title}</h4>\
<h5>{price}</h5>\
<h5>\
<a href="#">Kup teraz!</a>\
</h5>\
<p class="card-text">{description}</p>\
</div>\
<div class="card-footer">\
<small class="text-muted">★ ★ ★ ★ ★</small>\
</div>\
</div>\
</div>';
var result = bookTemplate.replace("{title}", this.title);
result = result.replace("{image}", this.image);
result = result.replace("{price}", this.price);
result = result.replace("{description}", this.description);
return result;
}
}
export function initBook() {
var newBook = new Book();
newBook.title = "Chów i hodowla trzody chlewnej";
newBook.image = "swinie.jpg";
newBook.price = "135zł";
newBook.description = "Podręcznik, który wyjaśnia jak chodować świnie.";
newBook.transform();
$("#newBook").html(newBook.transform());
}
最佳答案
所以您真的很接近解决方案。我稍微清理了您的代码,以便更清楚地了解您正在做的事情。首先在你的书课上,没有必要做所有的字符串替换并根据替换进行返回。你真正可以做的,以及你在这里看到的是使用一个简单的模板文字,并直接从传入的构造函数参数中进行替换。注意 ${} 语法,这是替换值。所以现在你有一个简单的书类,只有一个 bookTemplate 属性。
书籍类示例:
export class Book {
constructor(price, title, image, description) {
this.bookTemplate = `
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<a href="#">
<img class="mx-auto-d-block-card-img-top-fixed-top"
src="${image}" width="335" height="340" alt="${image}"
style="border: solid 1px #999999;"></a>
<div class="card-body">
<h4>${title}</h4>
<h5>${price}</h5>
<h5>\
<a href="#">Kup teraz!</a>
</h5>
<p class="card-text">${description}</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ★</small>\
</div>
</div>
</div>
`;
}
}
现在,在 initBook 函数中,我创建了一个简单的对象文字,其中包含需要在新的 Book 构造函数中传递的属性。然后我们获取 HTML 页面上元素的 ID,以便我们可以用我们的书籍模板替换它。我们使用之前和最后的参数创建一本新书,我们通过再次执行模板文字并从 Book 类调用 bookTemplate 属性,将新书模板分配给页面上的 HTML 目标。最后,我们只需调用函数 initBook() 即可将模板渲染到页面。
initBook 函数示例:
export function initBook() {
var params = {
title: "Chów i hodowla trzody chlewnej",
image: "swinie.jpg",
price: "135zł",
description: "Podręcznik, który wyjaśnia jak chodować świnie."
};
const book = document.getElementById("newBook");
const elements = new Book(params.price,
params.title, params.image,params.description);
console.log(elements);
book.innerHTML = `${elements.bookTemplate}`;
}
initBook();
要替换的目标 div 的 HTML 示例:
<div id="newBook"></div>
为了您的方便,这里有一个 working example上面提供的代码。
希望对你有帮助。
关于javascript - 如何使用javascript和HTML模板填充div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51949650/