有没有办法在没有真正的点击事件的情况下使用 onclick

Is there a way to use onclick without really onclick event?

本文关键字:事件 onclick 情况下 有没有      更新时间:2023-09-26

>我有这段代码:

<a href="" onclick="return false;" class="submitme">Add</a>

有没有办法在用户按下此按钮而不更改代码或添加 OnClick 事件时发出警报?

你可以简单地用JavaScript覆盖属性:

// Select the targeted element(s), in this case the first <a> element
// Note: You will need to replace this by a code that works
//       for your actual markup!
document.getElementsByTagName("a")[0].onclick = function() {
    alert("hi");
    return false;
}​​​;

演示:http://jsfiddle.net/WNZAP/

正如OP声明他们不允许更改HTML一样,并且jquery对他们不可用。

链接上没有"id"会使生活变得非常困难。因此,以下代码假定链接是页面上的第一个链接...

将此 JavaScript 放入页面的<head></head>部分...

<script type="text/javascript">
  window.onload = function() {
    document.getElementsByTagName("a")[0].onclick = function() {
      alert("Hello World");
      return false;
    }
  }
</script>

查看实时 JSFiddle 演示

没有事件就无法触发操作。但是,如果我答对了您的问题,您希望在不更改 HTML 的情况下触发警报。

最简单的方法是使用像jQuery这样的JavaScript库。因此,通过下载库并将其放置在您的项目中或通过 Google CDN 加载库:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

然后做这样的事情:

<script type="text/javascript">
$(document).ready(function(){
    $(".submitme").click(function(){
        alert("hello world");
    });
});
</script>