te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Call class instance method onclick javascript - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Call class instance method onclick javascript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Feb 16, 2012 at 20:23 James WoodsJames Woods 611 gold badge1 silver badge2 bronze badges 1
  • 1 If you want to do it right, and avoid causing a mess, don't use inline event handlers (onclick and friends). They just don't belong in your HTML. Learn about addEventListener() and all your code will bee much cleaner and manageable. – kapa Commented Feb 17, 2012 at 8:55
Add a ment  | 

3 Answers 3

Reset to default 7

http://jsfiddle/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/EyMCQ/2/

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

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

All of the answers above seem to over-plicate 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

发布评论

评论列表(0)

  1. 暂无评论