【问题标题】:How can I make a table in a cell a variable?如何使单元格中的表格成为变量?
【发布时间】:2012-03-15 09:36:40
【问题描述】:

我在单元格中有一个表格,显示用户使用按钮输入的数字(使用 onclick 和 showthis 函数。我需要能够将值存储为变量以便对其执行操作。我该如何这样做?
PS:我正在使用 JavaScript 和 HTML

<script language="JavaScript" type="text/javascript"> 
    function showthis(first){ 
        document.getElementById("displaycell").innerHTML+=first; 
    } 
</script>
<body> 
  <h1 align="center"> RPN Calculator </h1>
  <table summary align="center" border="1" cellpadding="1" cellspacing="3">
    <tr>
      <th id="displaycell" colspan="5" type="text"> </td>
    </tr>
    <tr>
      <td>
        <button type="button" onclick="showthis('1')">1</button>
      </td>
      <td>
        <button type="button" onclick="showthis('2')">2</button>
      </td>
      <td>
        <button type="button" onclick="showthis('3')">3</button>
     </td>
     <!-- ... -->

【问题讨论】:

  • 你有代码要显示吗?如果我们不知道自己在处理什么,我们将无能为力。
  • 我认为 HTML 需要修复(&lt;th&gt; 应该&lt;/td&gt; 关闭)。我会自己做,但我不知道这是真正的 HTML,还是这里的错字。

标签: javascript html button html-table


【解决方案1】:

首先,您不应该将+=innerHTML 一起使用。这意味着您最终将获得附加到单元格内部值的数字,而不是覆盖它。

function showthis ( number ) {
    var cell = document.getElementById('displaycell');
    cell.innerHTML = "";
    cell.appendChild( document.createTextNode( number ));
}

这将是一种更好的处理方式。

接下来,在 showthis 中,您最好将值存储在变量中,以便将来可以直接从 javascript 访问它。

var displayStore = 0;

function showthis ( number ) {
    var cell = document.getElementById('displaycell');
    cell.innerHTML = "";
    cell.appendChild( document.createTextNode( number ));

    // you can either do this in a variable local to the <td> DOM Object like so
    cell.currentDisplayNumber = number;

    //or in a global variable like so
    displayStore = number;
}

最后,要再次访问该变量,您可以从displaystore &lt;td&gt; 中读取它或从您的变量中读取它。

function DoStuff0 () {
    var number = Number( document.getElementById( 'displaycell' )).innerHTML;
    // rest
}

function DoStuff1 () {
    var number = document.getElementById('displaycell').currentDisplayNumber;
    // rest
} 

function DoStuff2 () {
    var number = displayStore;
    // rest
}

【讨论】:

  • RPN 计算器

  • 将代码放在您的问题中,而不是作为评论。这种形式没用。
【解决方案2】:

这是你想要的吗? http://jsfiddle.net/CWQY2/

HTML:

<h1 align="center"> RPN Calculator </h1>
<table summary align="center" border="1" cellpadding="1" cellspacing="3">
    <tr>
        <th id="displaycell" colspan="5"> </th> 
    </tr> 

    <tr> 
        <td> <button type="button" onClick="showthis('1')">1</button> </td> 
        <td> <button type="button" onClick="showthis('2')">2</button> </td> 
        <td> <button type="button" onClick="showthis('3')">3</button> </td>
    </tr>
</table>

JS:

function showthis(first){ 
    document.getElementById("displaycell").innerHTML += first; 
}
​

【讨论】:

    猜你喜欢
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2013-12-11
    相关资源
    最近更新 更多