单击JavaScript中的按钮

时间:2014-07-13 15:44:58

标签: javascript button

据我对JavaScript的知识非常有限,它可以获得有关页面上某些元素的各种信息,例如关于按钮。 JavaScript可以获取按钮的名称,类型,名称以及其中的文本。它甚至可以禁用按钮。但它可以模拟按钮上的点击吗?或者它只能由用户完成?

编辑1 (我对 Narxx 撰写的以下答案的回复):

这种方式似乎不起作用:

<html>
<head>
<script type="text/javascript">
document.getElementById('my-button').click();
</script>
</head>
<body>
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>

编辑2 (我对以下评论的回复 prash

这种方式也不起作用(模拟函数由 kangas 编写,由 TweeZz 修改,并且我来自 here ):

<html>
<head>
<script type="text/javascript">
function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}
simulate(document.getElementById("btn"), "click");
</script>
</head>
<body>
<button id="btn" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html> 

编辑3:(我对 Jonco98 撰写的以下答案的回复):

此代码也是我的问题的答案

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ClickButton()
{
document.getElementById('my-button').click();
}
</script>
</head>
<body onload="ClickButton()">
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>

编辑4:

请注意, naomik 给出的以下答案也能很好地解决我的问题。

3 个答案:

答案 0 :(得分:3)

我建议你这样做unobtrusively

<button id="my-button">The Time is?</button>

<script type="text/javascript">
  var b = document.getElementById("my-button");

  function displayTime(elem) {
    elem.innerHTML = Date();
  }

  b.addEventListener("click", function(event) {
    displayTime(this);
  });

  // fake the click
  b.dispatchEvent(new Event("click"));
</script>

jsfiddle demo

按钮加载并点击&#34;点击&#34;立即使用模拟事件。随后的点击将导致按钮时间更新。


这是另一个例子:

点击提交

后,时间将停止更新
<form id="my-form">
  <input name="time" />
  <input type="submit" />
</form>

<script type="text/javascript">
  var f = document.getElementById("my-form");

  function updateTime() {
    f.time.value = Date();
  }

  var interval = setInterval(updateTime, 1000);

  f.addEventListener("submit", function(event) {
    clearInterval(interval);  
    alert("the submitted time is: " + f.time.value);
    event.preventDefault();
  });

  // prepopulate form
  updateTime();
</script>

参考

答案 1 :(得分:1)

是的,您可以使用JavaScript模拟按钮上的点击:
HTML:

<button id="my-button">Click me</button>

JS:

document.getElementById('my-button').click();

那就是......你刚刚在按钮上触发了点击事件而没有实际点击它:)

答案 2 :(得分:1)

嗯,这不是替代答案。 @naomik建议答案已经存在,我同意这一点。

让我指出OP面临的问题,并且不清楚为什么他的实际代码不起作用。

实际代码:

<html>
   <head>
      <script type="text/javascript">
         document.getElementById('my-button').click();
      </script>
   </head>
   <body>
      <button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
   </body>
</html>

为什么没有触发事件的简单原因是因为,<button>当时没有绘制,你在控制台中会遇到此错误Cannot read property 'click' of null

在@naomik分享的第一个例子中,这似乎有效。原因是<script>被执行的地方。它不在<head>中,在<body>内,而<button>在脚本执行之前首先被绘制。

这很好,

<html>
   <head></head>
   <body>
      <button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
      <script type="text/javascript">
         document.getElementById('my-button').click();
      </script>
   </body>
</html>

除此之外,建议您通过dispatchEvent()addEventListener()来模拟和收听此事件。