我是jQuery的新手,我正在将以前的JavaScript代码重构为jQuery。我使用append()
和$(this).addClass()
方法,但似乎它们不起作用。我不知道问题是什么。
JavaScript代码是关于创建益智游戏(15个谜题)。我试图以jQuery方式将元素添加到HTML文件中。
var tile = function(i, j) {
this.seq = i * 4 + j + 1;
this.row = i + 1;
this.column = j + 1;
if (i * 4 + j != 15) {
$(this).addClass("block puzzle row" + this.row + " column" + this.column);
var xPosition = -j * 88;
var yPosition = -i * 88;
$(this).css("backgroundPosition", xPosition + "px " + yPosition + "px");
} else {
$(this).addClass("block row" + this.row + " column" + this.column);
$(this).attr('id', "blank");
}
}
function Init() {
var node = $("#imgContent"); // imgContent is a div
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
var t = new tile(i, j);
node.append(t);
}
}
// Generate the original picture before the start
Judge.isStart = false;
}
如何正确使用这些jQuery方法?
答案 0 :(得分:0)
$(this)
is actually defined by the invoker of the function, while explicit variables remain intact inside the function declaration block known as the enclosure.
你的函数中发生了什么tile(i,j)
,正在被明确调用,这意味着上下文或函数的“this”是window object
。具体到你的问题,this
绑定到全局对象,即window
。
例如,请考虑以下函数,
function myFunc(){
}
和
var myObj= { myFunc: myFunc};
如果您使用myObj.myFunc()
来电话;然后this
绑定到myObj
。
如果您直接致电myFunc()
,例如myFunc();
,
然后this
绑定到全局对象,即window
。
因此,调用没有后续父对象的函数通常会得到global object
,在大多数浏览器中都是window
对象。
答案 1 :(得分:0)
this
的上下文发生变化,将this
保留为变量,然后使用该变量。
var $this = this;
var tile = function(i, j) {
$this.// your code
}
答案 2 :(得分:0)
你错误地使用了$(this)。 当使用new调用tile()函数时,它将被实例化为一个对象并且&#39;这个&#39;成为该对象的引用。这样做,您可以使用&#39; this将值分配给其内部状态。&#39;句法。
jQuery主要用于操作文档对象模型(DOM)。通常你会将一个选择器传递给jQuery,它从文档中找到匹配的HTMLElements并返回它们进行操作。 $(this)在tile的上下文中传递了这个jQuery只返回给你的引用。
这里重要的部分是$(this)表示tile对象,而不是文档中的元素。 .css .addClass和.append函数不适用,因为它们适用于元素。您需要将选择器或元素传递给jQuery才能使用它们。
解决方案是在tile中创建一个可以附加到文档的元素。
https://jsfiddle.net/hxqduoef/2/
var tile = function(i, j) {
this.seq = i * 4 + j + 1;
this.row = i + 1;
this.column = j + 1;
// $("<div></div>") creates a new div element wrapped in the jQuery object, it isn't part of the document until it gets appended. saving to this allows further manipulations within this constructor.
this.element = $("<div>Tile at "+ i +" "+ j +"</div>");
if (i * 4 + j != 15) {
this.element.addClass("block puzzle row" + this.row + " column" + this.column);
var xPosition = -j * 88;
var yPosition = -i * 88;
this.element.css("backgroundPosition", xPosition + "px " + yPosition + "px");
} else {
this.element.addClass("block row" + this.row + " column" + this.column);
this.element.attr('id', "blank");
}
}
function Init() {
var node = $("#imgContent"); // imgContent is a div
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
var t = new tile(i, j);
node.append(t.element);
}
}
// Generate the original picture before the start
// Judge.isStart = false;
}
这会添加&#34; this.element&#34; property,将其设置为新的DIV元素,并在node.append(t.element)语句中引用它而不是t。
我希望这会有所帮助。