Add more behavior to existing onclick attribute in javascript(向 javascript 中的现有 onclick 属性添加更多行为)
问题描述
如何向现有的 onclick 事件添加更多行为,例如如果现有对象看起来像
how can i add more behaviour to existing onclick events e.g.
if the existing object looks like
<a href="http://abc" onclick="sayHello()">link</a>
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
</script>
我怎样才能在 onclick 中添加更多行为来执行以下操作
how can i add more behavior to the onclick that would do also the following
alert("say hello again");
sayGoodMorning()
最好的问候,凯沙夫
推荐答案
这是最肮脏的方式:)
<a href=".." onclick='sayHello();alert("say hello again");sayGoodMorning()'>.</a>
这是一个稍微理智的版本.将所有内容包装成一个函数:
Here's a somewhat saner version. Wrap everything into a function:
<a href=".." onclick="sayItAll()">..</a>
JavaScript:
JavaScript:
function sayItAll() {
sayHello();
alert("say hello again");
sayGoodMorning();
}
这是正确的方法.使用事件注册模型,而不是依赖 onclick
属性或属性.
And here's the proper way to do it. Use the event registration model instead of relying on the onclick
attribute or property.
<a id="linkId" href="...">some link</a>
JavaScript:
JavaScript:
var link = document.getElementById("linkId");
addEvent(link, "click", sayHello);
addEvent(link, "click", function() {
alert("say hello again");
});
addEvent(link, "click", sayGoodMorning);
addEvent
函数的跨浏览器实现如下(来自 scottandrew.com):
A cross-browser implementation of the addEvent
function is given below (from scottandrew.com):
function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be attached");
}
}
请注意,如果所有 3 个操作都必须按顺序运行,那么您仍应继续将它们包装在一个函数中.但是这种方法仍然优于第二种方法,虽然它看起来有点冗长.
Note that if all 3 actions must be run sequentially, then you should still go ahead and wrap them in a single function. But this approach still tops the second approach, although it seems a little verbose.
var link = document.getElementById("linkId");
addEvent(link, "click", function() {
sayHello();
alert("say hello again");
sayGoodMorning();
});
这篇关于向 javascript 中的现有 onclick 属性添加更多行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向 javascript 中的现有 onclick 属性添加更多行为


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06