我在以下函数中遇到“第二轮”文本替换问题。一切都会执行,没有 JS 错误等。唯一的问题是,当我对字符串变量执行第二个“替换”函数时,我无法替换"template"字符串中的“^”字符。
我尝试了一些不同的测试:只需运行“else”语句(非常简单的替换),尝试条件安排等,但我仍然无法将“次要考虑因素”附加到我的文本替换(甚至完全替换胡萝卜占位符)。
我正在使用 Shopify JSON API(如果有帮助的话)。 “options”是 GET 产品请求的结果,并使用“options”JSON 键及其值。
var createConfigsList = function(options) {
/* Container of options & product option we're working with */
var container = jQuery(".ta-OptionsContainer");
options.forEach(function(option, index, values) {
/* Name of option we're working with/also the label & select dropdown value */
var name = option.name;
/* Define formats for select boxes & value replacements */
var labelFormat = '<label>|</label>';
var selectFormat = '<select data-option="|" class="ta-CSelectDrop">';
var selectClose = '</select>';
var optionFormat = '<option data-value="|">^</option>';
if(name != "Title") { /* 'Title' is default Shopify variant option name */
/* Working HTML building variables */
var bLabel, bSelect, bOption, appendFormat;
/* Create the label & select box start */
bLabel = labelFormat.replace("|",name);
bSelect = selectFormat.replace("|",name);
/* List of values within this option set */
var values = option.values;
values.forEach(function(optVal) {
/* Define HTML building variable for this option tag */
var singleOption;
/* Create option; replace value placeholder w/ actual value */
singleOption = optionFormat.replace("|",optVal);
/* Secondary considerations for the text of the option tag */
if(name == "Length") {
singleOption.replace("^",optVal + " Length");
}
else if(name == "Depth") {
singleOption.replace("^",optVal + " Depth");
}
else {
/* If no special considerations, just do the replacement */
singleOption.replace("^",optVal);
}
/* Combine the option into the 'list' of options */
bOption = bOption + singleOption;
});
/* Close our select, and then append the new area to the display container */
appendFormat = bLabel + bSelect + bOption + selectClose;
container.append(appendFormat);
}
});
最佳答案
您需要将replace()
的结果赋回变量
singleOption = singleOption.replace("^", optval + " Length");
对于所有其他替换调用也类似。
关于javascript - 双字符串替换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46374991/