如何使用面向对象的javascript从控件调用函数?
在调用函数时,我们使用为该类创建的对象进行了调用。如何使用面向对象的javascript从控件调用函数?,javascript,jquery,Javascript,Jquery,在调用函数时,我们使用为该类创建的对象进行了调用。 objParent.SubChild(this.id)。在您的onchange处理程序中,您拥有this.SubChild(this.id),其中this指的是输入。而且由于从未调用子构造函数构造函数(或者至少我在任何地方都看不到它),因此任何对象都不会有子子构造函数方法。 要访问Child或Parent的实例,您应该使用IE8及更早版本中的addEventListener或attachEvent的适当事件绑定,或者如果必须使用jQuery,则
objParent.SubChild(this.id)。在您的
onchange
处理程序中,您拥有this.SubChild(this.id)
,其中this
指的是输入。而且由于从未调用子构造函数
构造函数(或者至少我在任何地方都看不到它),因此任何对象都不会有子子构造函数
方法。
要访问Child
或Parent
的实例,您应该使用IE8及更早版本中的addEventListener
或attachEvent
的适当事件绑定,或者如果必须使用jQuery,则使用jQuery的事件绑定。在这种情况下,您可以使用jQuery的proxy
函数或更新浏览器中每个函数的bind
方法指定回调中的内容。您在这里混合了很多东西(JS、HTML注入、事件处理)
以下是您应该如何操作(未经测试):
函数父函数(){
var parent=此;
this.Child=函数(){
var复选框=$('');
在('change',function()上的复选框{
parent.Child.SubChild(this.id);
});
$(“#liCheckbox”).append(复选框);
}
}
以下是一种方法:
function Parent() {
var parent = this;
this.Child = function () {
var checkBox = $('<input type="checkbox" name="ctlName" id="' + cltId + '" />');
checkBox.on('change', function() {
parent.Child.SubChild(this.id);
});
$('#liCheckbox').append(checkBox);
}
}
检查这把小提琴:这个.id
从哪里来?你想通过什么身份证?
var objParent = new Parent();//initializing object
function Parent() {
this.Child = function () {
var checkBox="";
checkBox +="<input type=\"checkbox\"
name=\"ctlName\"
id=\'" + cltId + "\'
onchange= 'objParent.SubChild(this.id)'//While calling the we have to call with object
/>";
$('#liCheckbox').append(checkBox);
}
this.Child.prototype = {
SubChild: function (id) {//this function not able to access
alert(this.first + ' ' + this.last+ ' '+id);
}
};
}
<ul>
<li id='liCheckbox'>
</li>
</ul>
function Parent() {
var parent = this;
this.Child = function () {
var checkBox = $('<input type="checkbox" name="ctlName" id="' + cltId + '" />');
checkBox.on('change', function() {
parent.Child.SubChild(this.id);
});
$('#liCheckbox').append(checkBox);
}
}
function Child() {
this.name = 'test';
}
Child.prototype = {
SubChild: function () {
alert(this.name);
}
}
function Parent() {
this.child = new Child();
};
new Parent().child.SubChild();