1

我有一个 jscript 对象。我在 div 中插入了一些 html,并尝试将事件单击附加到 html 标签,全部嵌入对象,如何访问 jquery click 事件函数中对象的方法和属性?

HTML 代码:

<div id="content"></div>

JAVASCRIPT代码:

<SCRIPT ...
jQuery().ready(function (){
    obj=new myobject("myobject1","#content"); //create object instance
    obj.dohtml(); //call method dohtml
});

//object I pass an objectname and a id from an html element 
function myobject(objectname,htmlid){

    this.name=objectname; //name of object 
    this.htmlid=htmlid;   //id where i try to create some html

    //say hello
    this.hello=function(){
       alert(hello); 
    }

    //do something with html
    this.dohtml=function(){

    //create an <p> element in a the html with id=htmlid 
    $(this.htmlid).html('<p id="'+this.name+'_myp" > my text </p>')     

    //click event on <p> id= this.name+'_myp"
    $("#"+this.name+'_myp').click(function(){
        alert(this.name); //i try to access property this.name in the object and dont work
        //how can access to this property from here

        this.hello(); //how can access to this method from here

    });

    $("#"+this.name+'_myp').click(this.hello()); //this dont work too why?

 } 

}
4

1 回答 1

2

您的范围在click回调中发生变化..所以您需要保存thisvar 存储:

var that = this;
$("#"+this.name+'_myp').click(function(){
    alert(that.name); //i try to access property this.name in the object and dont work
    that.hello(); //how can access to this method from here
}); 

对于第二部分:

您正在执行该函数并在执行时传递返回值this.hello(),如果您只想传递该函数,则可以不this.hello传递()

$("#"+this.name+'_myp').click(this.hello);

它适用,this因为您仍在范围内。

于 2012-09-01T20:29:29.490 回答