首页 > 解决方案 > 如何从返回函数中获取值并将其发送到 html 元素

问题描述

我一直在编写代码来保存图像上边界框的坐标。我能够从边界框中检索坐标。但我喜欢做的是将它们分别放在每个 HTML 元素下。

下图显示了从边界框收集的坐标:

在此处输入图像描述

在上图中,坐标在一行中。但我想单独获得这些值。

HTML:

<div class="actions">

          <input type="button" id="btnView" value="Display areas" class="actionOn" />
          <input type="button" id="btnReset" value="Reset" class="actionOn" />
          <input type="button" id="btn_add" value="add areas" class="actionOn" />
 </div>
  <br>
 <div id="output" class='output'> </div>
 <input type= "hidden" id="x" name ="x" value="-">
 <input type= "hidden" id="y" name ="y" value="-">
 <input type= "hidden" id="w" name ="w" value="-">
 <input type= "hidden" id="h" name ="h" value="-">

Javascript:

  var selectionExists;

  function areaToString (area) {
    return (typeof area.id === "undefined" ? "" : (area.id + ": ")) + area.x + ':' + area.y  + ' ' + area.width + 'x' + area.height + '<br />'
  }



  function output (text) {
    $('#output').html(text);
  }

  // Log the quantity of selections
  function debugQtyAreas (event, id, areas) {
    console.log(areas.length + " areas", arguments);
  };

  // Display areas coordinates in a div
  function displayAreas (areas) {
    var text = "";
    $.each(areas, function (id, area) {
      text += areaToString(area);
    });
    output(text);
  };

从上面的代码中,函数 DisplayAreas 用于使用'area.x'、'area.y'、'area.w'和'area.h'在一行中显示边界框的坐标,但我会喜欢将每个协调保存在每个 html 元素下,例如 x、y、w 和 h。

即,从图像中,当我按下显示区域按钮时,必须将坐标发送到 html 元素 x、y、w 和 h。并显示为

X: Y: W: H:

有人可以帮我解决这个问题。

标签: javascripthtmljquery

解决方案


用于document.getElementById()访问每个输入,并将其值设置为区域的相应属性。

  function displayAreas (areas) {
    var text = "";
    $.each(areas, function (id, area) {
      text += areaToString(area);
      document.getElementById("x").value = area.x;
      document.getElementById("y").value = area.y;
      document.getElementById("h").value = area.height;
      document.getElementById("w").value = area.width;
    });
    output(text);
  };

推荐阅读