如何从click方法调用自己的函数

时间:2012-11-19 12:11:48

标签: javascript onclick

我知道这听起来很愚蠢,但我不知道如何从“onclick”功能调用我的功能?

我创建了自己的类,我想做的是在一个类中调用我的函数。 我在onclick函数中尝试了各种各样的东西:

  • 功能(){this.getWidth()}
  • this.getWidth()
  • Test.getWidth()

函数Datagrid(_parent,_data) {     this.table = [];     this.parent = $(“#”+ _ parent)[0]? $(“#”+ _ parent):( $(“。”+ _ parent)[0]?$(“。”+ _ parent):( $(+ _ parent)[0]?$(_ parent):null));     this.data = _data;

this.Datagrid = function(parent,data)
{
    this.setParent(parent);
    if(data != null)
        this.setData(data);
    return this;
}


this.setParent = function(parent)
{
    return this.parent = $("#"+parent)[0] ? $("#"+parent) : ($("."+parent)[0] ? $("."+parent) : ($(+parent)[0] ? $(parent) : null));
}

this.getParent = function()
{return this.parent;}

this.setData = function(data)
{this.data = data;}

this.buildTable = function()
{
    var dtTbl = [];
    dtTbl.push('<table class="TimeSheetmainTable" cellpadding="10" cellspacing="0" border="0">');

    var style;

    //Header//////////////////////
    dtTbl.push('<tr class="header">');
    for (var cell in this.data.row[0].cell) {
        dtTbl.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
    }
    dtTbl.push('</tr>');
    //Content//////////////////////
    for(var r in this.data.row)
    {
        if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r1\'"'; }
        else { style = 'class="r2" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r2\'"'; }

        dtTbl.push('<tr ' + style + ' >');
        for(var c in this.data.row[r].cell)
        {
            dtTbl.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
        }
        dtTbl.push('</tr>');
    }
    //Footer//////////////////////
    dtTbl.push('<tr class="footer">');
    for (var cell in this.data.row[0].cell) {
        dtTbl.push('<td>&nbsp;</td>');
    }
    dtTbl.push('</tr></table>');

    this.parent.html(dtTbl.join(''));
}

this.buildTableDiv = function()
{
    var tableString = [];
    //Header//////////////////////
    tableString.push('<div class="container"><div class="header"><table><tr id="header">');
    for (var cell in this.data.row[0].cell) {
        tableString.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
    }
    tableString.push('</tr></table></div>');
    //Content//////////////////////
    tableString.push('<div class="content"><table>');
    var TD1 = new Object();
    var TD2 = new Object();

    for(var r in this.data.row)
    {
        if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r1\'"'; }
        else { style = 'class="r2" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'r2\'"'; }

        for(var c in this.data.row[r].cell)
        {
            if(c == 0)
            {   if(TD1.value != this.data.row[r].cell[c].value){
                    TD1.value = this.data.row[r].cell[c].value;
                    TD1.show = true;
                }
                else
                    TD1.show = false;
            }
            if(c == 1)
            {   if(TD2.value != this.data.row[r].cell[c].value){
                    TD2.value = this.data.row[r].cell[c].value;
                    TD2.show = true;
                }
                else
                    TD2.show = false;
            }   
            if(TD1.show && c == 0){//First line
                tableString.push('<tr id="content" ' + style + ' >');
                tableString.push('<td alt="' + this.data.row[r].cell[c].id + '"><input type="button" class="arrow_down" /> ' + this.data.row[r].cell[c].value + '</td>');
                for(var c = 0; c < this.data.row[r].cell.length - 1; c++)
                {
                    tableString.push('<td>&nbsp</td>');
                }
                tableString.push('</tr>');
            }
            else if(TD2.show && c == 1)//Second line
            {
                tableString.push('<tr id="content" ' + style + ' >');
                tableString.push('<td>&nbsp;</td><td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
                for(var c = 0; c < this.data.row[r].cell.length - 2; c++)
                {
                    tableString.push('<td>&nbsp</td>');
                }
                tableString.push('</tr><tr id="content" ' + style + ' ><td>&nbsp;</td><td>&nbsp;</td>');
            }
            else if(!TD2.show && c == 1)//third line (distincts second cells name)
            {
                tableString.push('<tr id="content" ' + style + ' >');
                tableString.push('<td>&nbsp;</td><td alt="' + this.data.row[r].cell[c].id + '">&nbsp;</td>');
            }
            else if(c > 1)//Rest filling (not ordered stuff)
            {
                tableString.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value.replace("","&nbsp;") + '</td>');
            }
        }
        tableString.push('</tr>');
        // $(".arrow_down").children(":nth-child(1)").click(function(){alert("test");});
    }
    tableString.push('</table></div>');
    //Footer//////////////////////
    tableString.push('<div class="footer"><table><tr id="footer">');
    for (var cell in this.data.row[0].cell) {
        tableString.push('<td>&nbsp;</td>');
    }
    tableString.push('</tr></table></div></div>');

    this.parent.html(tableString.join(''));

    // Setting width to all cells
    for (var i in this.data.row[0].cell)
    {
        cell = parseInt(i)+1;
        var h = this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
        var c = this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
        var f = this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
        var width = h > c ? h : (c > f ? c : f);

        this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
        this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
        this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
    }
    // this.activateScroller(0);
}

this.getScrollerWidth = function()
{
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
     // Append our div, do our calculation and then remove it 
    $('body').append(div); 
    var w1 = $('div', div).innerWidth(); 
    div.css('overflow-y', 'scroll'); 
    var w2 = $('div', div).innerWidth(); 
    $(div).remove(); 
    return (w1 - w2); 
}

this.activateScroller = function(value)
{
    var d = [];
    d.push('<div style="height: ' + this.parent.children(":first").children(".content").height() + '; width:20px; background:#FFF"><div style="background:#333; height:200">&nbsp;</div></div>');

    this.parent.children(":first").children(".content").scrollTop(value);
}

expandParent = function()
{
    alert(this.parent);
}

};

我是基于javascript的makig datagrid。我不被允许使用jQuery UI。 我的数据网格是由表格组成的。现在我尝试在用户名等td元素中添加一个按钮 问题是我无法在我的类中访问我的函数而不用实例。是不是可以在没有实例的情况下做到这一点?

1 个答案:

答案 0 :(得分:1)

使用generateHTML函数生成html后,onclick on div的处理程序会丢失“this”的上下文。更具体地说,div的onclick处理程序中的this指的是DOM中的div节点。

要访问getWidth方法,您必须使其可用于全局上下文或(更好的解决方案)执行以下操作:

// new version of your generateHTML function
this.generateHTML() {
   var str = [];
   str.push('<div><input type="button" value="button"/></div>');
   var that = this;
   $("#testDiv").append(str.join('')).find('button:first').click(function() {that.getWidth()});
}

编辑: 为了进一步解释上面的代码如何工作,这里是带注释的简化示例。

​​Test = function() {    
    this.generate = function() {
        var newnode = $('<button>click me</button>');        
        $("body").append(newnode);
        // "cache" this in a variable - that variable will be usable in event handler
        var that = this;
        // write event handler function here - it will have access to your methods by using "that" variable
        newnode.click(function(e) {
            // here this refers to button not Test class
            // so we have to "reach" to outer context to gain access to all methods from Test
            that.doSomething('learn');
        })
    }
    this.doSomething = function(x) {
        alert('do it: '+x);            
    }
}

// initialize part
// make instance of Test "class"
t = new Test();
// generate the button (clicking on a button will essentialy fire Test.doSomething function in a context of "t"
t.generate();