我刚刚开始学习 JavaScript 中的 OOP,一开始就遇到了一些问题。
我想在我自己的类中使用 jQuery,如下所示:
var myclass = function() {
this.attr1 = false;
this.target1 = false;
this.func1 = function() {
this.target1.text(this.attr1);
console.log(this.attr1);
}
}
var testObj = new myclass();
$.extend(testObj, $);
testObj.attr1 = "Hello World";
testObj.target1 = $("#targetcontainer");
testObj.func1();
<div id="targetcontainer">some1 out there?</div>
但是我的容器没有更改文本。你能帮我吗?
最佳答案
在尝试使用选择器查询元素之前,您需要确保 dom 已创建。
var myclass = function() {
this.attr1 = false;
this.target1 = false;
this.func1 = function() {
this.target1.text(this.attr1);
console.log(this.attr1);
}
}
$(document).ready(function() {
var testObj = new myclass();
$.extend(testObj, $);
testObj.attr1 = "Hello World";
testObj.target1 = $("#targetcontainer");
testObj.func1();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="targetcontainer">some1 out there?</div>
关于javascript - 使用 jQuery 扩展我的类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29163852/