gpt4 book ai didi

javascript - 如何使用 jQuery 中的 if 语句更改输出文本?

转载 作者:行者123 更新时间:2023-12-04 03:37:26 25 4
gpt4 key购买 nike

我在网站上实现了愿望 list 功能,主要基于本教程 Tuts Plus Create AJAX Wishlist Plugin .它按预期工作,除了 Rest API 调用的库存输出 - 它返回“instock”或“outofstock”,我正在用头撞砖墙试图弄清楚如何让它返回格式化字符串(例如,“有货!”包裹在一个跨度中)代替。我昨天大部分时间都在尝试以我知道的任何方式格式化它,但没有成功。

以下是插件 PHP 文件中代码的相关部分:

register_rest_field('product',
'stock',
array(
'get_callback' => 'rest_stock',
'update_callback' => null,
'schema' => null
)
);

function rest_stock($object,$field_name,$request){

global $product;

$id = $product->get_id();

if ($id == $object['id']) {
return $product->get_stock_status();
}
}

结果通过这个简化的 JS 输出:

.done(function(response){
$('.wishlist-items').each(function(){
var $this = $(this);
$.each(response,function(index,object){
$this.append('<li class="wishlist-item" data-product="'+object.id+'"><span class="wishlist-item-stock">'+object.stock+'</span></li>');
});
});
})

有人可以给我指明正确的方向吗?!谢谢!

最佳答案

感谢@CBroe 的指导,我成功了:

function rest_stock($object,$field_name,$request){

global $product;

$id = $product->get_id();
$status = $product->get_stock_status();

if ($id == $object['id']) {

if ( 'instock' == $status ) {
$stockformatted = '<span class="wishlist-is">In stock!</span>';
}

if ( 'outofstock' == $status ) {
$stockformatted = '<span class="wishlist-oos">Out of stock</span>';
}

return $stockformatted;
}
}

关于javascript - 如何使用 jQuery 中的 if 语句更改输出文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66637730/

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