在javascript中检索和修改HTML div



我有一个异步javascript函数,它设置div的innerHMTL属性,比如:

async function getProductsRecommendationsAsync(){
const product = await ...
const mySection = document.querySelector(".my-section");
mySection.innerHTML = renderProduct(product);
}
function renderProduct(product){
return [
'<div>',
'<a href="' + productUrl + '" class="product__anchor">',
'<img class="product__img" src="' + product.image + '" alt="'+ product.title +'"/>',
'<p class="product__title">' + product.title + '</p>',
'</a>',
'</div>'
].join("");
}

在HTML中,我有一个产品(与上面的结构相同(和div,函数修改:

<div class="product">
<a href="..." class="product__anchor">
<img class="product__img" src="..."/>
<p class="product__title">'Trousers'</p>
</a>
</div>
<div class="my-section"></div>

我希望避免在两个地方重复用于呈现产品的代码如何从renderProductjavascript函数中的productdiv中检索HTML并修改其值在实际用例中,用于呈现产品的代码超过300行HTML。

您可以删除静态HTML代码并将所有内容移动到Javascript。对于初始化代码,您还可以处理窗口的加载事件。

要求不要在静态HTML中复制可以在JS函数中呈现的结构。

那么,为什么不删除产品的静态HTML,而是在加载时调用这个Javascript来设置第一个产品"Trousers"呢。

const mySection = document.querySelector(".my-section");
const initialProduct = {"title": "Trousers", "Url": theurl, "image": theimage};
mySection.innerHTML = renderProduct(initialProduct);

注意:我假设给定代码中的productUrl实际上应该是product。Url,但如果没有,则需要更改。

所以基本上,正如我所理解的,您有一些div.mySection元素。您确实成功加载了数据。但是,我想您有一个独立的元素:div.product,您也希望使用renderProduct函数加载数据。

问题是,在renderProduct函数中,您生成了一个未分类的div元素,但您确实希望在这个独立元素中有一个类。在这种情况下,我考虑稍微更改一下renderProduct

function renderProduct(product){
return [
'<a href="' + productUrl + '" class="product__anchor">',
'<img class="product__img" src="' + product.image + '" alt="'+ product.title +'"/>',
'<p class="product__title">' + product.title + '</p>',
'</a>',
].join("");
}

那么,getProductsRecommendationsAsync将是:

async function getProductsRecommendationsAsync(){
const product = await ...
const mySection = document.querySelector(".my-section");
mySection.innerHTML = `<div>${renderProduct(product)}</div>`;
}

然后用加载您的独立产品

<div class="product">
</div>

然后,用JS以任何你想的方式瞄准这个元素:

const productStandaloneElement = ..
productStandaloneElement.innerHTML = renderProduct(product);

最新更新