【问题标题】:If Else, Else If, Else - Based on String In URLIf Else, Else If, Else - 基于 URL 中的字符串
【发布时间】:2014-05-20 11:31:33
【问题描述】:

你好, 我试图让我的 javascript 识别每个页面上的文件夹。根据文件夹名称,我想使用 if else 语句将该文件夹名称添加到我的 innerHTML 中。我无法让它与 if else、else if、else 语句一起运行。

这是 HTML sn-p:

<div id="countryVal"></div>

还有 javascript:

var outputData = document.getElementById('clothingVal');

if (window.location.search.search(/Men/)) {
document.getElementById('clothingVal');
outputData.innerHTML = outputData.innerHTML + ': ' + 'Australia';
}

else if (window.location.search.search(/Women/)) {
document.getElementById('clothingVal');
outputData.innerHTML = outputData.innerHTML + ': ' + 'New Zealand';
}

else {outputData.innerHTML = outputData.innerHTML + ': ' + '';
};

非常感谢任何建议。

【问题讨论】:

  • 无法理解您要完成的工作。只是document.getElementById('clothingVal'); 的行什么也不做。
  • 嗯...JS有'clothingVal',HTML有"countryVal"

标签: javascript string url if-statement innerhtml


【解决方案1】:

没有必要,但 switch 可能比 if elseif else 更好。我发现它们更易于管理,当您将来可能想要放置一个新过滤器时。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

但是保留当前代码,您应该清理变量以使其更具可读性。您还应该将此代码放在 onload 或 onready 语句中。并且也许我们 indexOf 超过了正则表达式(你需要逃避反斜杠才能找到它们像 /\/Men\// 这样会变得混乱)How to check whether a string contains a substring in JavaScript? p>

这是未经测试的,但应该与您所追求的一致。

window.onload = function() {
    var outputData = document.getElementById('clothingVal');

    if ( window.location.indexOf("/Men/") != -1 ) {
        outputData.innerHTML = outputData.innerHTML + ': ' + 'Australia';
    } else if ( window.location.indexOf("/Women/") != -1 ) {
        outputData.innerHTML = outputData.innerHTML + ': ' + 'New Zealand';
    } else {
        outputData.innerHTML = outputData.innerHTML + ': ' + '';
    };
}

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多