我正在为电子商务购物车页面开发 AB 测试。我们有大约 100 个样式名称的列表,我们不会接受这些样式名称的返回。
我们在这些特定样式的产品显示页面上显示消息,但如果购物车中的任何产品与符合条件的样式名称列表匹配,我们还希望在购物车页面上强化此消息。
我首先创建一个包含所有限定样式名称的数组变量(例如此处缩写的)。然后,我循环遍历每个购物车项目标题标签并检查该元素的 .text() 。如果 .text() 与我正在寻找的样式名称之一匹配,那么我将继续将消息附加到购物车项目标题标签下方。
这是我编写的脚本,但是,在我的开发工具片段中本地运行此脚本时,我没有看到预期的结果:
var styleList = ['Astawia Loafer','Another Style','So On','So Forth'];
var finalSaleMessage = '<span><strong>Final sale! </strong>No returns on our best deals.</span>'
function checkStyleName(value,arr){
var result = false;
for (var i = 0; i < arr.length; i++){
var name = arr[i];
if(name == value){
result = true;
break;
}
}
return result;
}
$('.crt-heading--item').each(function(){
if (checkStyleName($('.crt-heading--item').text(),styleList) == true) {
// append the message
}
})
如果社区提供任何意见,我们将不胜感激。如果您需要更多信息,请告诉我。
谢谢!
最佳答案
可以稍微简化一下。
无需每次都发送数组。
包含的用法。
文本的格式似乎是 BRAND PRODUCT_NAME CATEGORY
。您可能需要拆分或执行某些操作来获取 PRODUCT_NAME
。
devmiguelopz
指出的 this
的用法
var styleList = ['Astawia Loafer','Another Style','So On','So Forth'];
var finalSaleMessage = '<span><strong>Final sale! </strong>No returns on our best deals.</span>'
// OLD SUGGESTION
/*
$('.crt-heading--item').each(function(){
if (styleList.includes($(this).text()) {
// append the message
}
*/
// This will iterate on the elements
$('.crt-heading--item').each(function(){
// Iterate on the styleList
var styleListLength = styleList.length;
for(var i = 0, i < styleListLength; i++){
// Check if the name has entry from styleList
if($(this).text().includes(styleList[i])){
// DO STUFF
}
}
})
// We re running a loop inside a loop in this case.
// There may be better ways of doing this with .some/.filter/.map
在此处查看 .includes
可以为您做什么:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
关于javascript - 检查每个购物车标题项的特定样式名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61143458/