gpt4 book ai didi

javascript - 根据从下拉列表中选择的选项渲染模板

转载 作者:行者123 更新时间:2023-12-02 21:39:08 26 4
gpt4 key购买 nike

我一直在尝试根据用户从下拉列表中选择的选项来渲染模板,但不幸的是这对我不起作用。我的代码如下所示

const beer = {
name: 'Belgian Wit',
brewery: `Steam Whistle Brewery`,
keywords: ['pale', 'cloudy', 'spiced', 'crisp'],
texto: 'hello'
};


function renderKeywords(keywords) {
return `
<select multiple="true">
${keywords.map(keyword => `<option>${keyword}</option>`)}
</select>
`;
}

function renderHtml(texto) {
return `
<input type="text" id="${texto}" value=""/>
`;
}

function selectElement(elem) {
if (elem.value === 'multiple') {
document.getElementById('p2').innerHTML = $ {
renderKeywords(beer.keywords)
};
} else {
document.getElementById('p2').innerHTML = $ {
renderHtml(beer.texto)
};
}
}

const markup = `
<div class="beer">
<h2>${beer.name}</h2>
<p class="brewery">${beer.brewery}</p>
<select onchange="selectElement(this)">
<option>Select</option>
<option value="multiple">Multiple</option>
<option value="single">Single</option>
</select>
<div id="p2"></div>
</div>
`;

document.getElementById('panel').innerHTML = markup;
<head>
<title></title>
</head>

<body>
<div id="panel"></div>
</body>

最佳答案

似乎是一个错字,伙计。 $ {renderKeywords(beer.keywords) }$ { renderHtml(beer.texto) } 行抛出错误,因为您试图传递 ${ } 从模板文字到 innerHTML 属性,但不带反引号。

尽管反引号和方括号不是必需的,因为您的 renderKeywords() 已经返回一个字符串。

...
if (elem.value === 'multiple') {
document.getElementById('p2').innerHTML = $ {
renderKeywords(beer.keywords)
};
} else {
document.getElementById('p2').innerHTML = $ {
renderHtml(beer.texto)
};
}
...

const beer = {
name: 'Belgian Wit',
brewery: `Steam Whistle Brewery`,
keywords: ['pale', 'cloudy', 'spiced', 'crisp'],
texto: 'hello'
};

function renderKeywords(keywords) {
return `
<select multiple="true">
${keywords.map(keyword => `<option>${keyword}</option>`)}
</select>
`;
}


function renderHtml(texto) {
return `
<input type="text" id="${texto}" value=""/>
`;
}

function selectElement(elem) {
if (elem.value === 'multiple') {
document.getElementById('p2').innerHTML = renderKeywords(beer.keywords);
} else {
document.getElementById('p2').innerHTML = renderHtml(beer.texto);
}
}

const markup = `
<div class="beer">
<h2>${beer.name}</h2>
<p class="brewery">${beer.brewery}</p>
<select onchange="selectElement(this)">
<option>Select</option>
<option value="multiple">Multiple</option>
<option value="single">Single</option>
</select>
<div id="p2"></div>
</div>
`;

document.getElementById('panel').innerHTML = markup;
<head>
<title></title>
</head>

<body>
<div id="panel"></div>
</body>

关于javascript - 根据从下拉列表中选择的选项渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60410998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com