【问题标题】:Double String Replace Issue双字符串替换问题
【发布时间】:2017-09-23 01:00:04
【问题描述】:

我在以下函数中遇到了“第二轮”文本替换问题。一切都执行了,没有 JS 错误等。唯一的问题是,当我对字符串变量执行第二个“替换”函数时,我无法替换“模板”字符串中的“^”字符。

我尝试了一些不同的测试:只运行'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);

    }
});

【问题讨论】:

    标签: javascript json shopify


    【解决方案1】:

    你需要将replace()的结果赋值给变量

    singleOption = singleOption.replace("^", optval + " Length");
    

    对于所有其他替换调用也是如此。

    【讨论】:

    • 天哪,我真是个笨蛋。谢谢。
    猜你喜欢
    • 2010-10-04
    • 2015-10-11
    • 2011-11-24
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多