gpt4 book ai didi

Javascript 实例变量显示为未定义

转载 作者:行者123 更新时间:2023-11-28 12:27:10 25 4
gpt4 key购买 nike

我创建了一个 Javascript 对象,它将点击监听器添加到某些类上,然后调用 PHP 函数以从 MYSQL/PHP 驱动的后端生成结果。后端工作正常(并且结果正确返回)。我遇到一个问题,即实例认为实例的属性(字符串)为空,即使我直接为该属性分配了值也是如此。

这是我的代码:

//Workout Videos Class
var Workout = function(offset, limit, element, categoryId) {
this.offset = offset;
this.html = "";
this.limit = limit;
this.element = element;
this.categoryId = categoryId
var self = this;

jQuery(this.element).on("click", function(e) {
e.preventDefault();
self.seeMoreClick(this, self.videoCallBack, self)
});
}

Workout.prototype.seeMoreClick = function(item, videoCallBack, thisArg) {
jQuery.ajax({
type : 'POST',
dataType : 'json',
url : 'api/get-videos',
data : 'category_id=' + this.categoryId + "&offset=" + this.offset + "&limit=" + this.limit,
success : function(data) {
videoCallBack.call(thisArg, data, item);
}
});
}

Workout.prototype.videoCallBack = function(response, item) {
this.offset = response.offset;
if(response.videos) {
jQuery(response.videos).each(function(key, video) {
this.html += "<div class='col-md-4' data-related-video='" + video.videoId + "'>";
this.html += '<a href="#" class="dashboard-video"></a>';
this.html += '<div class="video-information">';
this.html += '<h5 class="tk-bebas-neue">' + video.videoName + '</h5>';
this.html += '<p>' + video.videoDesc + '</p>';
this.html += '<p>Equipment: ';
jQuery(video.equipment).each(function(equipKey, equipmentItem) {
this.html += '<a href="#" class="equipment-item" data-equipment-id="' + equipmentItem.equipmentId + '">' + equipmentItem.equipmentName + '</a>';
});
this.html += "</p>";
this.html += '<div class="video-rating" data-rel="' + video.videoId + '" data-user-id="' + video.userId + '">';


this.html += "</div>";
this.html += '</div>';
this.html += "</div>";
});
} else {
this.html += "<div class='col-md-12'>No more videos to show</div>";
}
console.log(this.html);
jQuery("#" + jQuery(this.element).attr("data-related") + " .col-md-8").append(this.html);
}

我遇到的问题是在“videoCallBack”函数中,我使用该函数传递给 AJAX 函数,以确保它在所有代码运行之前解决。当我在设置后直接将其登录到控制台时,“this.html”属性显示为空。谁能明白为什么会发生这种情况?谢谢

最佳答案

这是代码中 this 更改的结果。在 forEach block 内,“this”引用了不同的对象,因此您要将所有 HTML 添加到完全不同的对象中。

一个简单的修复方法是保存对此的引用:

Workout.prototype.videoCallBack = function(response, item) {
var self = this;
self.offset = response.offset;
if(response.videos) {
jQuery(response.videos).each(function(key, video) {
self.html += "<div class='col-md-4' data-related-video='" + video.videoId + "'>";
...

关于Javascript 实例变量显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26997141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com