$row["Name"], "color" => $row["Color"]; } echo json_encod-6ren">
gpt4 book ai didi

javascript - 在 javascript 中作为数组成员存储的函数/命令

转载 作者:行者123 更新时间:2023-11-28 19:36:03 27 4
gpt4 key购买 nike

test.php 上的 PHP 代码:

<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
echo "failed to connect:" . mysqli_connect_error();
}

$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
array_push($cars, array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
echo json_encode($cars);

然后在 html 页面上添加 jQuery/javascript 代码:

var iNL1 = document.getElementById("itemNameLink1").innerHTML;
var iNL2 = document.getElementById("itemnameLink2").innerHTML;
var iNL3 = document.getElementById("itemNameLink3").innerHTML;

var iNLarr = [iNL1, iNL2, iNL3];
i = 0;

$.get("test.php", function($cars){
$.each($cars, function(){
iNLarr[i] = this.name;
i++;
});
}, "json");

谁能告诉我为什么这不起作用,我在 iNLarr[i] 上得到空引用。我猜我无法像我所做的那样将命令存储在数组中。谁能告诉我一种方法来做到这一点。

最佳答案

如果要将“命令”放入数组中,则需要将函数放入:

iNRarr = [ 
function(html) {
document.getElementById("itemNameLink1").innerHTML = html;
}, function(html) {
document.getElementById("itemNameLink2").innerHTML = html;
}, function(html) {
document.getElementById("itemNameLink3").innerHTML = html;
}
];

然后你像这样调用函数:

$.get("test.php", function($cars){
$.each($cars, function(i, car){
if (iNLarr[i]) {
iNLarr[i](car.name);
}
});
}, "json");

关于javascript - 在 javascript 中作为数组成员存储的函数/命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25873198/

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