簡體   English   中英

如何獲取 jQuery 中的特定元素。獲取“數據”

[英]How can you get specific elements in jQuery.get “Data”

所以我有數據(data.html)

$(document).ready(function(){
    setTimeout(function(){
        $.get("/computers/{{computer.id}}/live", function(data){
            console.log(data)
        });
    }, 5000);
});

問題是“數據”是"/computers/{{computer.id}}/live"的整個源代碼我想在 html 中獲取特定的 ID

/computers/{{computer.id}}/live(HTML 文件):

<script type="text/javascript" src="{{ url_for('static', filename='jquery.js') }}"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<script>
 $(document).ready(function(){
      setTimeout(function(){
            $('#id').load("")
        }, "{{timer}}");
      });
</script>
<div id="id">
<span class="badge badge-light"  id ="cpu">{{computer.cpu_usage_procentage}}</span>
<span class="badge badge-light"  id ="memory">{{computer.memory_usage_procentage}}</span>
</div>

How do I select the cpu and memory id and console.log their value (in data.html of course) or more specifically putting them in the data.html page

您可以使用 jQuery 默認 function 來解析 html 來執行此操作:

 var html = `<div id="id"> <span class="badge badge-light" id ="cpu">44%</span> <span class="badge badge-light" id ="memory">66%</span> </div>`; var parsed = $(html); var cpuUsage = parsed.find("#cpu").text(); var memUsage = parsed.find("#memory").text(); console.log(`CPU usage ${cpuUsage} - Mem usage ${memUsage}`);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您還可以在服務器中創建 API 以提供 JSON 格式的信息:

/computers/{{computer.id}}/livejson:

{
  cpuUsage: "{{computer.cpu_usage_procentage}}",
  memUsage: "{{computer.memory_usage_procentage}}"
}

在客戶端:

 $.get("/computers/{{computer.id}}/livejson", function(json){
    var data = JSON.parse(json);
    console.log(`CPU usage ${data.cpuUsage} - Mem usage ${data.memUsage}`);
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM