我收到了以下代码:
var image1 = 'aaa.jpg';
var image2 = 'bbb.jpg';
var image3 = 'ccc.jpg';
var image4 = 'ddd.jpg'; // all dynmically created
current = 1; // dynamically changing value, in this case between 1 and 4
我现在需要的是提醒alert(image1);
但是这样:alert(image + current);
这种方式有可能吗?我希望我能清楚地解释我的需要。
答案 0 :(得分:1)
这样做:
this.image1 = "aaa.jpg";
alert(this["image" + "1"]);
答案 1 :(得分:0)
从我看来,我认为你走的是正确的道路。但是有些事情需要考虑......
var image1 = 'aaa.jpg';
alert(eval('image'+current));
祝你好运!
我看到你编辑了这个问题,把动态变量放在引号中。干得好。
答案 2 :(得分:0)
我用一个用户发布它的方式解决了它并删除了他的答案(为什么?):
alert(eval('image'+current));
答案 3 :(得分:0)
正如评论中的建议并基于评论中的PHP代码:创建一个JavaScript数组来存储数据,而不是创建大量变量。你可以完成它,例如:
创建包含所有图片的字符串
<?php
$images = '';
while($row = mysqli_fetch_assoc($result)) {
$images .= ( $images ? ',' : '' ) . '"' . $row['image'] . '"';
}
?>
<强>输出强>
var images = [<?php print $images; ?>];
alert (images[0]);
答案 4 :(得分:0)
您明确使用集合,因此在这种情况下您应该创建一个数组结构:
<?php
$images = [];
while ($row = mysqli_fetch_assoc($ergebnis)) {
$images[] = $row['image'];
}
?>
<script type="text/javascript">
var images = <?php echo json_encode($images) ?>;
</script>
然后,您可以通过以下方式引用每个图像路径: images[0]
。