如何在要添加的IF语句中添加ELSE

时间:2018-12-27 17:14:07

标签: javascript jquery html json

在当前的DEMO中,您可以搜索一个或多个值(1001、1002、1003),并且将提取JSON属性功能。

因此,如果您搜索:

1001, 1002, 1003

您得到:

RANK_BY_CD: 1001 => 26

RANK_BY_CD: 1002 => 212

RANK_BY_CD: 1003 => 248

var data = [];

    $(document).ready(function () {
    $("#button").click(function (any_function_variable_name) {
        var searchIds = new Set($('#searchBox').val().split(',').map(s => s.trim()));
        data.features.forEach(({ properties: { CDUID, RANK_BY_CD } }) => {
            if (searchIds.has(CDUID)) {
          $("ul")
          .append(`<li> <strong>RANK_BY_CD: </strong>${CDUID} => ${RANK_BY_CD}`);
            } else {
	$("ul")
  	return(`<li> <strong>RANK_BY_CD: </strong>${CDUID} => undefined`);
}
        });
    });
});

    function getdata() {
        var xmlhttp = new XMLHttpRequest();
        var url = "https://api.myjson.com/bins/6oj58";
        //var data = [];
        xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                data = JSON.parse(this.responseText);
            }
        };
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    getdata();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="searchBox" type="text"></textarea>
    <button id="button">
        Search
    </button>
    <div>
        <ul></ul>
    </div>

我正在尝试添加else语句,如果您搜索不匹配的值,例如:

0001

它将返回:

RANK_BY_CD: 0001 => undefined

我在if else语句的else部分尝试了.append,return,document.write,但我却一无所获或出错。

1 个答案:

答案 0 :(得分:3)

然后,您应该迭代searchIds而不是data。在这种情况下,最好在检索时将数据转换为键/值对。

旁注:我建议使用fetch API,它比XMLHttpRequest使用起来简单得多:

var data = {};

$(document).ready(function () {
    $("#button").click(function (any_function_variable_name) {
        $("ul").empty();
        var searchIds = new Set($('#searchBox').val().split(',').map(s => s.trim()));
        searchIds.forEach(id => 
            $("ul").append(`<li><strong>RANK_BY_CD: </strong>${id} => ${data[id]}</li>`)
        );
    });
});

function getdata() {
    fetch("https://api.myjson.com/bins/6oj58").then(resp => resp.json()).then(resp => {
        data = Object.assign({}, ...resp.features.map(
            ({ properties: { CDUID, RANK_BY_CD } }) => ({ [CDUID]: RANK_BY_CD }))
        );
    });
}

getdata();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="searchBox" type="text"></textarea>
<button id="button">
    Search
</button>
<div>
    <ul></ul>
</div>