调用类实例方法 onclick javascript

发布于 2025-01-05 23:29:09 字数 480 浏览 0 评论 0 原文

我有一个 javascript 文件,其中包含包含方法函数的类。我想知道如何从 onClick 事件调用类实例方法。

function MyClass()
{
    this.instanceData = "Display Me";

    this.DisplayData = function()
    {
        document.write(this.instanceData);
    }
}

var classInstance = new MyClass();

我如何从 onClick 事件调用 classInstance 上的 DisplayData 函数。例如:

<button onClick="classInstance.DisplayData()">Click Me!</button>

这不起作用,但可以帮助我澄清我想要做什么。有什么建议吗?

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.

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:

<button onClick="classInstance.DisplayData()">Click Me!</button>

Which doesn't work, but helps me clarify what I'm looking to do. Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笔芯 2025-01-12 23:29:09

http://jsfiddle.net/EyMCQ/1/

正如您所注意到的,这不起作用,因为您声明的 var 保留在执行块的范围内。如果删除 var,它就会起作用,因为 classInstance 现在位于全局范围内。

function MyClass() {
    this.instanceData = "Display Me";

    this.DisplayData = function() {
        alert(this.instanceData);
    }
}

classInstance = new MyClass();​

并这样称呼它:

<button onClick="classInstance.DisplayData.call(classInstance)">Click Me!</button>​

http://jsfiddle.net/EyMCQ/2/

http://jsfiddle.net/EyMCQ/1/

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.

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>​

http://jsfiddle.net/EyMCQ/2/

呆头 2025-01-12 23:29:09

假设您的代码在全局范围内,则可以正常工作,但在加载页面后无法使用 document.write 。所以:

function MyClass()
{
    this.instanceData = "Display Me";

    this.DisplayData = function()
    {
        alert(this.instanceData); // <=== only change here
    }
}

var classInstance = new MyClass();

...与您的 onclick 属性配合得很好。 实例 | source

document.write 主要用于期间页面加载。如果您在页面加载后调用它,则意味着 document.open 会清除当前文档并用您编写的内容替换。如果您想在页面加载后附加到页面,请使用 createElementappendChild,通过innerHTML。例如:

var p = document.createElement('p');
p.innerHTML = "Hi there";
document.body.appendChild(p);

...将包含“Hi There”的段落附加到页面。

但是,我强烈建议您不要使用 onclick 属性等,尤其是因为它们需要访问全局变量和函数,并且我主张避免将全局变量和函数用于尽你所能(并且你几乎可以完全避免它们)。相反,使用连接事件处理程序的现代方法: addEventListener 和(支持 IE8 及更早版本)attachEvent< /代码>

因此,更改您的示例,使其不会创建任何全局变量:(

(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
    }
})();

事件名称是带有 addEventListener 的“click”,带有 attachEvent 的“onclick”。)

请注意, 按钮看起来像这样:

<button id="theButton">Click Me!</button>

...并且您的代码在按钮已经放在页面上之后运行(例如,您的脚本是 位于页面底部或响应某些事件而运行)。

现在,每次都检查是否使用 addEventListener 还是 attachEvent 很痛苦。另外,您可能不希望需要使用的每个元素都有一个 id。这是使用良好的 JavaScript 库的地方,例如 jQuery原型YUI闭包,或其他任何一个都是有用的。它们为您平滑了事件内容(以及许多其他特性),并提供了有用的功能,可以通过 id 以外的方式定位元素(在许多情况下,支持几乎所有 CSS 样式选择器,甚至在没有 querySelector / 的旧版浏览器<一href="http://www.w3.org/TR/selectors-api/#queryselectorall" rel="nofollow">querySelectorAll 内置。

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:

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 during the page load. If you call it after page load, it implies a document.open which wipes out the current document and replaces it 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:

var p = document.createElement('p');
p.innerHTML = "Hi there";
document.body.appendChild(p);

...appends a paragraph containing "Hi there" to the page.

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.

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.)

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 page or 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 others is 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.

后eg是否自 2025-01-12 23:29:09

上面所有的答案似乎都让情况变得有点复杂。

我只是使用这个:

MyClass = new function() {
    this.instanceData = "Display Me";

    this.DisplayData = function() {
        alert(this.instanceData);
    };
};

这是按钮:

<button onClick="MyClass.DisplayData()">Click Me!</button>

这是一个演示这一点的小提琴:
小提琴

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文