Javascript If语句,不起作用

Javascript If Statement, not working

本文关键字:不起作用 语句 If Javascript      更新时间:2023-12-25

我有一个JavaScript函数,我想用它来获取当前URL,如果=后面有任何值,那么它应该放在一个ID为name的文本框中。然而,目前,当我打开页面时,完整的URL显示在文本框中,所以我希望有某种条件,只有在only=之后有值时,它才会显示

function DisplayProdCod(value) {
    var URLstring = window.location.href;
    if (URLstring.indexOf('=')) {
        var ProductCode = URLstring.split("=").pop();
        document.getElementById('Name').value = ProductCode;
        document.getElementById('Name').style.backgroundColor = #C8C8FF;
    }
}

典型的URL可以是

http://brmappsvr:7018/Enquiries/CMFRAME.html

http://brmappsvr:7018/Enquiries/CMFRAME.html?ProductCode=1BLK970/07

更改条件以检查是否返回-1,如下所示:

function DisplayProdCod(value) {
    var URLstring = window.location.href;
    if (URLstring.indexOf('=') != -1) {
        var ProductCode = URLstring.split("=").pop();
        document.getElementById('Name').value = ProductCode;
        document.getElementById('Name').style.backgroundColor = #C8C8FF;
    }
}

当您要搜索的字符没有出现在字符串中时,indexOf函数返回-1。由于每个数字(0除外)都是真的,所以你的if条件每次都满足。因此,您应该更好地检查索引是否大于-1,即

if (URLstring.indexOf('=') > -1) {
    ...
}

只需执行URLstring.split('='),然后检查结果的长度。如果是2,则使用结果[1],否则出现问题。

试试这个示例

html

<input type="text" id="Name"/>
<input type="button" onclick="DisplayProdCod();" value="click"/>

JS

function DisplayProdCod() {
    var URLstring = window.location.href;
    alert(URLstring);
    if (URLstring.indexOf("=") > -1) {
        var ProductCode = URLstring.split("=").pop();
        document.getElementById("Name").value = ProductCode;
        document.getElementById('Name').style.backgroundColor ="#C8C8FF";
    }
}

请参阅DEMO在这个演示中,我正在搜索一个字符串"fiddle",您可以在程序中将其替换为"="

注意:在您的代码中,当您设置背景颜色时,会漏掉一个双引号应该低于

document.getElementById('Name').style.backgroundColor ="#C8C8FF";