如何动态更改onClick处理程序? [英] How to change onClick handler dynamically?

查看:87
本文介绍了如何动态更改onClick处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信有一百万篇关于这方面的文章,但令人惊讶的是我很难找到一些东西。

我有一个简单的脚本,用于在初始化时为< A> 链接设置onClick处理程序



当我立即运行这个 时,得到一个'foo'提醒框,我希望只在点击时得到提醒在链接。



我做错了什么愚蠢的事情? (我试过点击=和onClick =)...

 < script language =javascript> 

函数init(){

document.getElementById(foo)。click = new function(){alert('foo'); };
}

< / script>

< body onload =init()>
< a id =foohref =#>点击运行foo< / a>
< / body>






编辑: I将我接受的答案更改为jQuery答案。 'MárÖrlygsson'的答案在技术上是正确的答案到我原来的问题(点击应该是 onclick 应该被删除),但是我强烈建议任何人在他们的代码中直接使用document.getElementById(...)并使用 jQuery

解析方案

b
$ b

  $('#foo')。click(function(){alert('foo');}); 

或者如果您不希望它跟随链接href:

  $('#foo')。click(function(){alert('foo'); return false;}); 


I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something.

I have a simple script where I want to set the onClick handler for an <A> link on initialization of the page.

When I run this I immediately get a 'foo' alert box where I expected to only get an alert when I click on the link.

What stupid thing am I doing wrong? (I've tried click= and onClick=)...

<script language="javascript">

    function init(){

        document.getElementById("foo").click = new function() { alert('foo'); };
    }

</script>

<body onload="init()">
    <a id="foo" href=#>Click to run foo</a>
</body>


Edit: I changed my accepted answer to a jQuery answer. The answer by 'Már Örlygsson' is technically the correct answer to my original question (click should be onclick and new should be removed) but I strongly discourage anyone from using 'document.getElementById(...) directly in their code - and to use jQuery instead.

解决方案

jQuery:

$('#foo').click(function() { alert('foo'); });

Or if you don't want it to follow the link href:

$('#foo').click(function() { alert('foo'); return false; });

这篇关于如何动态更改onClick处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆