调用类实例方法 onclick javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9318501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call class instance method onclick javascript
提问by James Woods
I have a javascript file with classes which contain method functions. I was wondering how to go about calling a class instance method from an onClick event.
我有一个包含方法函数的类的 javascript 文件。我想知道如何从 onClick 事件调用类实例方法。
function MyClass()
{
this.instanceData = "Display Me";
this.DisplayData = function()
{
document.write(this.instanceData);
}
}
var classInstance = new MyClass();
How would I call the DisplayData function on classInstance from an onClick event. For example:
我将如何从 onClick 事件调用 classInstance 上的 DisplayData 函数。例如:
<button onClick="classInstance.DisplayData()">Click Me!</button>
Which doesn't work, but helps me clarify what I'm looking to do. Any suggestions?
这不起作用,但可以帮助我澄清我想要做什么。有什么建议?
回答by sankargorthi
As you notice, this does not work, because the var you've declared, stays in the scope of the executing block. If you remove the var, it'll work, because classInstance
is now in the global scope.
正如您所注意到的,这不起作用,因为您声明的 var 仍在执行块的范围内。如果您删除 var,它将起作用,因为classInstance
现在在全局范围内。
function MyClass() {
this.instanceData = "Display Me";
this.DisplayData = function() {
alert(this.instanceData);
}
}
classInstance = new MyClass();?
and call it like this:
并这样称呼它:
<button onClick="classInstance.DisplayData.call(classInstance)">Click Me!</button>?
回答by T.J. Crowder
Your code works just fine assuming it's at global scope, except that you can't use document.write
after the page is loaded. So:
假设它在全局范围内,您的代码就可以正常工作,除非您document.write
在页面加载后无法使用。所以:
function MyClass()
{
this.instanceData = "Display Me";
this.DisplayData = function()
{
alert(this.instanceData); // <=== only change here
}
}
var classInstance = new MyClass();
...works fine with your onclick
attribute. Live example| source
document.write
is primarily for use duringthe page load. If you call it after page load, it implies a document.open
which wipes out the current document and replacesit with the content you write. If you want to append to the page after page load, use createElement
and appendChild
, setting the content of the element via innerHTML
. For instance:
document.write
主要用于页面加载期间。如果您在页面加载后调用它,它意味着 adocument.open
会清除当前文档并将其替换为您编写的内容。如果要在页面加载后附加到页面,请使用createElement
和appendChild
,通过 设置元素的内容innerHTML
。例如:
var p = document.createElement('p');
p.innerHTML = "Hi there";
document.body.appendChild(p);
...appends a paragraph containing "Hi there" to the page.
...在页面上附加一个包含“Hi there”的段落。
However, I urge you not to use onclick
attributes and such, not least because they require access to global variables and functions, and I advocate avoiding having global variables and functions to the extent you can (and you can almost completely avoid them). Instead, use modern methods of hooking up event handlers: addEventListener
and (to support IE8 and earlier) attachEvent
.
但是,我敦促您不要使用onclick
属性等,尤其是因为它们需要访问全局变量和函数,并且我提倡尽可能避免使用全局变量和函数(并且您几乎可以完全避免它们)。相反,使用连接事件处理程序的现代方法:addEventListener
和(以支持 IE8 及更早版本)attachEvent
。
So changing your example so that it doesn't create any globals:
因此,更改您的示例,使其不会创建任何全局变量:
(function() {
function MyClass()
{
this.instanceData = "Display Me";
this.DisplayData = function()
{
alert(this.instanceData);
}
}
var classInstance = new MyClass();
// ...and hook it up
var button = document.getElementById("theButton");
if (button.addEventListener) {
button.addEventListener('click', function() {
classInstance.DisplayData();
}, false);
}
else if (button.attachEvent) {
button.attachEvent('onclick', function() {
classInstance.DisplayData();
});
}
else {
// Very old browser, complain
}
})();
(Note that the event name is "click" with addEventListener
, "onclick" with attachEvent
.)
(请注意,事件名称是“click”和addEventListener
,“onclick”和attachEvent
。)
That assumes the button looks like this:
假设按钮如下所示:
<button id="theButton">Click Me!</button>
...and that your code runs after the button has already been put on the page (e.g., your script is at the bottom of the pageor runs in response to some event).
...并且您的代码在按钮已放置在页面上之后运行(例如,您的脚本位于页面底部或运行以响应某些事件)。
Now, it's a pain to check whether to use addEventListener
or attachEvent
every single time. Also, you may not want every element you need to work with to have an id
. This is where using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several othersis useful. They smooth over the event stuff (and many other idiosyncrasies) for you, and provide useful features for locating elements in ways other than by id
(in many cases, supporting nearly all CSS-style selectors, even on older browsers that don't have querySelector
/ querySelectorAll
built in.
现在,检查是否使用addEventListener
或attachEvent
每次都很痛苦。此外,您可能不希望您需要使用的每个元素都有一个id
. 这就是使用优秀的 JavaScript 库(如jQuery、Prototype、YUI、Closure或其他几个库中的任何一个)很有用的地方。它们为您平滑事件内容(以及许多其他特性),并提供有用的功能以通过除 by 以外的方式定位元素id
(在许多情况下,支持几乎所有 CSS 样式选择器,即使在没有querySelector
/querySelectorAll
内置。
回答by Ziki
All of the answers above seem to over-complicate the situation a bit.
上面的所有答案似乎都使情况变得过于复杂。
I simply use this:
我只是用这个:
MyClass = new function() {
this.instanceData = "Display Me";
this.DisplayData = function() {
alert(this.instanceData);
};
};
And here is the button:
这是按钮:
<button onClick="MyClass.DisplayData()">Click Me!</button>
And here is a fiddle that demonstrates this: Fiddle