如何动态分配JavaScript“onclick”属性? [英] How do you assign a JavaScript 'onclick' attribute dynamically?

查看:134
本文介绍了如何动态分配JavaScript“onclick”属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript动态创建一个按钮,同时分配ID,类型等属性以及onclick以触发功能。

I'm creating a button dynamically using JavaScript and at the same time assigning attributes such as 'ID', 'type' etc and also 'onclick' in order to trigger a function.

除了'onclick'的分配外,一切正常。单击时,该按钮不会按预期触发该功能。我正在尝试运行的功能是'导航(-1)',如下所示。

All works fine apart from the assignment of the 'onclick'. When clicked, the button is not triggering the function as it is supposed to. the function I'm trying to run is 'navigate(-1)' as seen below.

我哪里出错?

这是我的代码:

function loadNavigation() {
var backButton;
backButton = document.createElement('input');
backButton.ID = 'backButton';
backButton.type = 'button';
backButton.value='Back';
backButton.onclick = 'navigate(-1)';
document.body.appendChild(backButton);
}


推荐答案

正如对方说你应该分配一个函数。

As the other said you should assign a function.

只是想指出在这种情况下你要传递一个值,所以你需要分配一个匿名函数(或一个内联定义的命名函数)喜欢

Just wanted to point out that in this case you want to pass a value so you need to assign an anonymous function (or a named function defined inline) like

button.onclick = function() {otherfunction(parameter)};

如果您要分配的功能不需要参数,您可以直接使用它

If the function you want to assign does NOT require a parameter you can use it directly

button.onclick = otherfunction;

请注意,在这种情况下没有括号

Note that there is no parenthesis in this case

button.onclick = otherfunction(); // this doesn't work

无效,因为它会调用其他函数一解析

won't work as it will call otherfunction as soon as it is parsed

这篇关于如何动态分配JavaScript“onclick”属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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