【问题标题】:html print variable valuehtml打印变量值
【发布时间】:2015-09-01 15:18:54
【问题描述】:

现在我有这段代码,我想在屏幕上(不是弹出窗口)打印按钮被点击的次数的值。我想我会设置一个 var index = 0 并在每次单击它时递增它......但我不确定如何更改屏幕上的变量值。例如,现在它已经被点击了 0 次。当我单击按钮时,我希望那里的值

另外.. 我希望这都是 HTML 格式.. 如果可能,请不要使用 php 或 javascript。

<html>
<head>
<script type="text/javascript">
function getVote(int)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("poll").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();


if(typeof(Storage)!=="undefined")
  {
  if (localStorage.clickcount)
    {
    localStorage.clickcount=Number(localStorage.clickcount)+1;
    }
  else
    {
    localStorage.clickcount=1;
    }
  document.getElementById("result").innerHTML="You have voted " + localStorage.clickcount + " times before this session";
  }
else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
  }
}

</script>

</head>
<body bgcolor=#5D003D>
<div id="poll">

<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p><form>
<input type="Button" class="voteButton" name="vote" value="Vote" onclick="getVote(this.value)" />
</form>
</div>
</body>
</html>

【问题讨论】:

  • DEMO,制作 plunker 或 jsFiddle!或者至少是 SO 的代码 sn-p
  • 这个问题有点难理解。请随意添加您工作的 JSFiddle,但请注意,这不能仅在 HTML 中完成,您肯定也需要 JS。
  • 我想飞。但没有飞机、机翼或人造物体。有时我们想要的只是不切实际。
  • 纯 HTML 无法做到这一点。

标签: html button


【解决方案1】:

不,至少没有 JavaScript 是做不到的。这是一个简单的例子。首先,当页面上的所有图像/脚本/内容都加载完毕时,我告诉窗口对象给我一个叫喊声。这意味着在我尝试将事件侦听器附加到它包含的任何元素之前,我可以确定包含在正文中的 HTML 将存在。

接下来,当我知道内容已加载时,我告诉按钮让我知道它何时被点击。

最后,当按钮被点击时,我递增全局变量pressCount,然后将其值设置为 span 元素的内容。

<!doctype html>
<html>
<head>
<script>
"use strict";
window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
    document.getElementById('myButton').addEventListener('click', onButtonPressed, false);
}

var pressCount = 0;
function onButtonPressed(evt)
{
    ++pressCount;
    document.getElementById('countOutput').innerText = pressCount;
}
</script>
</head>
<body>
    <button id='myButton'>PressMe</button> has been pressed <span id='countOutput'>0</span> times.
</body>
</html>

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2011-03-30
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多