带有输入,按钮和图片的Javascript动态表

时间:2018-05-31 06:09:29

标签: javascript image html-table

我正在尝试创建一个包含文本输入框的表格行的页面,一个用于加载图像和图像框的按钮。它还包括一个开始和停止循环图像。

现在我编写的代码除了循环功能之外还有效,我相信showpic可以简化。你觉得怎么样?

var count = -1

function addline() {
  var table = document.getElementById("a");
  var row = table.insertRow(-1);
  var cell1 = row.insertCell(0)
  var cell2 = row.insertCell(1)
  var cell3 = row.insertCell(2)
  var temp = count;
  cell1.innerHTML = "<input type='text'/>";
  cell2.innerHTML = "<button>Load</button>";
  cell2.setAttribute("onclick", "showpic(this)");
  count++;
  cell2.setAttribute("id", count);
}

function showpic(a) {
  var table = document.getElementById("a");
  var cell3 = table.rows[a.id].getElementsByTagName("td")[2]
  cell3.innerHTML = "<img><img/>";
  var link = table.rows[a.id].getElementsByTagName("td")[0].getElementsByTagName("input")[0].value;
  cell3.getElementsByTagName("img")[0].setAttribute("src", link);
}

function slides() {
  var i = 0;
  myvar = setInterval(function() {
    showpic(i);
    i++
  }, 1000);
}

function stopslides() {
  clearInterval(myvar);
}
<html>

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Erg 11</title>
</head>

<body>
  <button onclick="addline()">Add</button>
  <button onclick="slides()">Start</button>
  <button onclick="stopslides()">Stop</button>
  <p>
    <table border="1" id="a">
    </table>
  </p>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

您将错误的值传递给http://localhost:81/weatherapi/index.php/Cities/index/1 showpic。试试这个

startSlides
var count = -1

function addline() {
  var table = document.getElementById("a");
  var row = table.insertRow(-1);
  var cell1 = row.insertCell(0)
  var cell2 = row.insertCell(1)
  var cell3 = row.insertCell(2)
  var temp = count;
  cell1.innerHTML = "<input type='text'/>";
  cell2.innerHTML = "<button>Load</button>";
  cell2.setAttribute("onclick", "showpic(this)");
  count++;
  cell2.setAttribute("id", count);
}

function showpic(element) {
  var table = document.getElementById("a");
  var cell3 = table.rows[element.id].getElementsByTagName("td")[2]
  cell3.innerHTML = "<img><img/>";
  var link = table.rows[element.id].getElementsByTagName("td")[0].getElementsByTagName("input")[0].value;
  cell3.getElementsByTagName("img")[0].setAttribute("src", link);
}

function slides() {
  var i = 0;
  var rows = document.getElementById("a").rows;
  myvar = setInterval(function() {
    showpic(rows[i].getElementsByTagName("td")[1]);
    i++;
    if (i > count) {
      stopslides();
    }

  }, 1000);
}

function stopslides() {
  clearInterval(myvar);
}