gpt4 book ai didi

javascript - 尝试从函数返回一个对象

转载 作者:行者123 更新时间:2023-12-01 03:08:56 24 4
gpt4 key购买 nike

抱歉,但无法找到此问题的答案。我正在 html 上查找项目并将其推送到一个对象,但我无法弄清楚为什么这个函数不返回该对象?我可以毫无问题地进行安慰。

function getItem(obj){
var itemsObj;
$('.info').on('click', function(){
itemsObj = {};
$this = $(this);
itemsObj.gameImg = $this.parent().parent().find('img').attr('src');
itemsObj.gameTitle = $this.parent().parent().find('p').text();
itemsObj.gameInfo = $this.parent().parent().find('h2').text();
// console.log(itemsObj);
return itemsObj;
});
}
//getItem();
console.log(getItem());
<div class="col-lg-3 game">
<div class="view view-first">
<img src="img/deathstranding.jpg"/>
<div class="mask">
<h2>Death Stranding</h2>
<p>Death Stranding is an upcoming action video game developed by Kojima Productions and published by Sony Interactive Entertainment for PlayStation 4. It is the first game by game director Hideo Kojima and his company following the 2015 disbandment of Kojima Productions as a subsidiary of Konami and subsequent reformation as an independent studio.</p>
i<a href="#" class="info">♥</a>
</div>
</div>

最佳答案

它没有返回任何内容的原因是因为您返回了 click 事件监听器函数的数据而不是 getItem() 函数,也没有办法返回就这样吧

function getItem(obj){
var itemsObj;
$('.info').on('click', function(){
itemsObj = {};
$this = $(this);
itemsObj.gameImg = $this.parent().parent().find('img').attr('src');
itemsObj.gameTitle = $this.parent().parent().find('p').text();
itemsObj.gameInfo = $this.parent().parent().find('h2').text();
// This sends data to click event listener not getItem()
return itemsObj;
});
}

为了接收您想要的项目,您应该实现回调

function getItem(callback){
var itemsObj;
$('.info').on('click', function(){
itemsObj = {};
$this = $(this);
itemsObj.gameImg = $this.parent().parent().find('img').attr('src');
itemsObj.gameTitle = $this.parent().parent().find('p').text();
itemsObj.gameInfo = $this.parent().parent().find('h2').text();
// call the callback function parameter and send itemsObj as argument, callback function then received the argument as you wanted it to be. Then execute stuff from there.
callback(itemsObj);
});
}

// send a function instead for getItem to call when all is well
getItem(function (data) {
// here you will receive the data
console.log(data);
// stuff
});

提示:如果您想要一个更酷的解决方案来实现成功失败场景,请检查 jQuery Deffered JavaScript Promises

希望有帮助

关于javascript - 尝试从函数返回一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45971902/

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