jquery在我的js代码之前已加载到我的html中。 然后在我的puzzle.js中,我有:
<script type="text/javascript">
sendRequest();
function sendRequest() {
$.ajax({
url: "{{ path('prestaShop_test_get_screenShots') }}",
success:
function (data) {
$('#links').append($("<div />", {
class: 'gallery',
}).append($("<a />", {
href: 'assets/screenshots/' + data,
title: data
}).append($("<img />", {
src: 'assets/screenshots/' + data,
alt: data,
style: 'width:400px ; height: 200px'
}))
)
);
},
complete: function () {
// Schedule the next request when the current one's complete
setInterval(sendRequest, 5000); // The interval set to 5 seconds
}
});
};
</script>
class Puzzle {
constructor(ID, Name, Status) {
this.ID = "main" + ID;
this.Name = Name;
this.Status = Status;
this.mainDiv = "";
}
generateDiv() {
this.mainDiv = '<div id="' + this.ID + '"/>';
$(this.mainDiv).addClass("puzzle");
}
}
$(document).ready(function() {
var puzzle = new Puzzle(1, "MyPuzzle", 1);
puzzle.generateDiv();
$("#Puzzles").append(puzzle.mainDiv);
})
.puzzle {
width: 200px;
height: 200px;
background: black;
border 1px solid white;
}
并且div get带有漂亮的ID字段,但该类没有。实际上,我对div“ jquery-style”所做的任何操作都无济于事(但也没有控制台错误)
我注意到,在检查器(chrome)中,div显示为
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Puzzles"></div>
不知道这是什么意思或相关性。
我做错了什么?
答案 0 :(得分:2)
您需要存储div的jQuery版本:
this.mainDiv = $(this.mainDiv).addClass("puzzle");
否则,您将类添加到在下一行中丢弃的内容中。
考虑discussed here是什么:
var $div = $("<div>", {id: "foo", "class": "a"});
Mark Baijens的评论:
通常在包含jQuery对象的变量前加一个美元符号
您可以执行以下操作:
class Puzzle {
constructor(ID, Name, Status) {
this.ID = "main" + ID;
this.Name = Name;
this.Status = Status;
this.$mainDiv = null;
}
generateDiv() {
this.$mainDiv = $("<div>", {id: this.ID, "class": "puzzle"});
}
}
$(document).ready(function() {
var puzzle = new Puzzle(1, "MyPuzzle", 1);
puzzle.generateDiv();
$("#Puzzles").append(puzzle.$mainDiv);
})
.puzzle {
width: 200px;
height: 200px;
background: black;
border 1px solid white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Puzzles"></div>