Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - JavaScript循环比较字符串JSON(JavaScript loop compare string JSON)

I'm having trouble with comparing a simple loop and if condition here, trying to compare a string from a return JSON file and compare it.

(我在比较简单的循环时遇到麻烦,如果在这里遇到条件,则尝试比较返回的JSON文件中的字符串并进行比较。)

Here is my JSON file

(这是我的JSON文件)

"interface": [["enp1s0", "e4:3a:6e:09:bb:d3", "10.0.0.250/24", "fe80::e63a:6eff:fe09:bbd3/64"], ["enp2s0", "e4:3a:6e:09:bb:d4", "192.168.0.250/24", "fe80::e63a:6eff:fe09:bbd4/64"], ["enp3s0", "e4:3a:6e:09:bb:d5", "unavailable", "unavailable"], ["enp4s0", "e4:3a:6e:09:bb:d6", "unavailable", "unavailable"]]}

and this is my js code that tries to compare if the the ip address is defined to fill mt table

(这是我的js代码,尝试比较ip地址是否定义为填充mt表)

  function getinterfaces() {
    $.getJSON('/getips/', function(data) {
      //  document.getElementById("enp1s0").setAttribute("data-value", data.interface)

      for (i = 1; i < 3; i++) {
        if (data.interface[i][2] === 'unavailable') {
          document.getElementById('enp' + i + 's0').textContent = data.interface[i][2];
        } else {
          document.getElementById('enp' + i + 's0').textContent = 'NOT ASSIGNED';
        }
      }
    });
  }

I have a table to fill from the json file

(我有一张表要从json文件填充)

......
<td><span id="en1ps0"></span></td> .....
 <td><span id="en2ps0"></span></td> .....
 <td><span id="en3ps0"></span></td> .....
  <td><span id="en4ps0"></span></td>......
  ask by ilvista translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

(尝试这个)

JS:

(JS:)

function getinterfaces() {
      $.getJSON('/getips/', function(data) {

        for (let interface of data.interface) {
          const name = interface[0];
          const ip = interface[2];
          const element = document.getElementById(name);
          if (element) {
            if (ip !== 'unavailable') {
              element.textContent = ip;
            } else {
              element.textContent = 'NOT ASSIGNED';
            }
          }
        }
      })
    }

HTML :

(HTML:)

<td><span id="enp1s0"></span></td>
<td><span id="enp2s0"></span></td>
<td><span id="enp3s0"></span></td>
<td><span id="enp4s0"></span></td>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...