gpt4 book ai didi

javascript - AJAX 完成对象字面量后执行函数

转载 作者:行者123 更新时间:2023-11-28 17:48:07 25 4
gpt4 key购买 nike

我正在尝试将数据添加到动态模式中。仅当数据添加到模型后,模态才应显示出来。我尝试使用行 $.when(Ss.pieceInfo(piece)).then(Ss.showInfo()); 来实现此目的,但似乎两个函数同时执行。什么

var Ss = {
$modal: $('#piece-modal'),
$title: $('.piece-title'),
$artist: $('.piece-artist'),
$info: $('.piece-info'),


init: function() {
this.bindEvents();
},

bindEvents: function() {
$('.piece').on("click", function(e) {
e.preventDefault();
var piece = $(this).data('slug');

//This doesn't seem to have any effect
$.when(Ss.pieceInfo(piece)).then(Ss.showInfo());
});
},

pieceInfo: function(piece) {
console.log(piece);
$.getJSON(Kirby.baseUrl + '/api/v1/work/' + piece, function(data) {

$.each(data, function(key, val) {
Ss.$title.html(val.title);
Ss.$artist.html(val.artist);
Ss.$info.html(val.text);
})
});
},

showInfo: function() {
var height = $('.primary-info').height();
console.log(height)
Ss.$modal.addClass('modal-active')
Ss.$modal.css('transform','translate3D(0, calc(100% - '+ height +'px), 0)');
},
};

$(document).ready(function(){
Ss.init();
});

最佳答案

这是因为您没有在 Ss.pieceInfo() 方法中返回 Promise,导致它立即得到解决。 As per the documentation for $.when() :

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

为此,您只需稍微更改该方法:返回 $.getJSON promise 。

pieceInfo: function(piece) {
return $.getJSON(Kirby.baseUrl + '/api/v1/work/' + piece, function(data) {

$.each(data, function(key, val) {
Ss.$title.html(val.title);
Ss.$artist.html(val.artist);
Ss.$info.html(val.text);
})
});
},

关于javascript - AJAX 完成对象字面量后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240308/

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