如何在pugs java脚本中使用node.js var ?



我将一个变量从服务器端(节点)文件传递到客户端pug文件-

const prods_arr = [
{Types: "Electronic",Brand: "Apple", Products: [ "MacBook Pro", "MacBook Air", "Mac Mini"]}, 
{Types: "Electronic", Brand: "Dell", Products: [ "Inspioren", "Latitude"]},
{Types: "Electronic", Brand: "Samsung", Products: [ "Galaxy S20", "Galaxy S10"]}
];
res.render("./products", {
pageTitle: "products",
prods: prods_arr
});

我在pug文件中显示prods数组的内容-

select(name="type" onchange="change()")#type
option(value="Null") "Type"
for (products in prods) {
option(value=products.Type) #{procucts.Type}
}
select(name="brands")#brands
option(value="Null") "Brand"

现在我想在脚本标签中使用prods数组。

script.
function change() {
var type = document.getElementById("type").value;
var brand = document.getElementById("brands");

for (brands in prods) {
if (brands.Type == type) {
const brandOption = new Option(brands.Brand, brands.Brand);
brand.add(brandOption, undefined);
}
}
}

我如何在脚本标签中使用我的prods数组??

必须对数组进行字符串化

script.
function change() {
const type = document.getElementById("type").value;
const brand = document.getElementById("brands");

for (const prod of !{JSON.stringify(prods)}) {
if (prod.Types === type) {
const brandOption = new Option(prod.Brand, prod.Brand);
brand.add(brandOption, undefined);
}
}
}

!{JSON.stringify(prods)}返回数组的逐字JSON字符串,您可以在JavaScript中使用JSON作为对象/数组文字。

输出为

<script>function change() {
const type = document.getElementById("type").value;
const brand = document.getelementById("brands");

for (prod in [{"Types":"Electronic","Brand":"Apple","Products":["MacBook Pro","MacBook Air","Mac Mini"]},{"Types":"Electronic","Brand":"Dell","Products":["Inspioren","Latitude"]},{"Types":"Electronic","Brand":"Samsung","Products":["Galaxy S20","Galaxy S10"]}]) {
if (prod.Types === type) {
const brandOption = new Option(prod.Brand, prod.Brand);
brand.add(brandOption, undefined);
}
}
}</script>

您的代码中有多个其他错误。这是工作代码

select(name="type" onchange="change()")#type
option(value="Null") Type
each prod in prods 
option(value=prod.Types) #{prod.Types}
select(name="brands")#brands
option(value="Null") Brand
script.
function change() {
const type = document.getElementById("type").value;
const brand = document.getElementById("brands");

for (const prod of !{JSON.stringify(prods)}) {
if (prod.Types === type) {
const brandOption = new Option(prod.Brand, prod.Brand);
brand.add(brandOption, undefined);
}
}
}

你不能那样做。prods是一个服务器端变量,您必须调整它才能从客户端访问它。最好的建议是不要那样做。但是,在将其发送到客户端之前,最好将其呈现为HTML中的JSON字符串,然后在客户端JS中读取。

的例子:

<meta name="prods" content="{{ JSON.stringify(prods) }}">
const prods = JSON.parse(document.querySelector('meta[name="prods"]').content);
console.log(prods);

相关内容

  • 没有找到相关文章

最新更新