从自动生成的列表中选择时,将“img id”更改为“document.getElementById”的解决方案

Solution for changing' img id' with 'document.getElementById' when selecting from auto generated list

本文关键字:自动生成 document 解决方案 getElementById id img 选择 列表      更新时间:2023-09-26

自动生成的列表中进行选择时更改图像 ID 的解决方案此代码: <?php foreach(glob('pano/*.png') as $filename):?> <li><a href="javascript:chgpano()"><?php $path_parts = pathinfo ($filename); echo $path_parts['filename'], "'n";?></a> </li> <?php endforeach; unset( $filename);?>

生成一个屏幕,其中包含每个文件的按钮。函数 chgpano:

function chgpano()
{
ima = document.getElementById("tonto");
init();
}

更改分配给变量"ima"的 img Id。"tonto"的内容需要反映所选的图像。

以下内容不起作用,但确实显示了意图:

  function chgpano()
{
    img id="tonto" src= ('pano/'+ variable with text from button selected)
ima = document.getElementById("tonto");
init();
}

我看到了一个类似的问题,但因不清楚而被拒绝

试试这个:

// PHP can look like
$liA = '';
foreach(glob('pano/*.png') as $f){
  $path_parts = pathinfo($f);
  $liA .= "<li><a href='javascript:chgpano($f)'>{$path_parts['filename']}></a></li>";
}
echo $liA;
// JavaScript can look like + some goodies
var doc = document; // get in the habit of declaring variables
function E(e){
  return doc.getElementById(e);
}
var tonto = E('tonto');
function chgpano(f){
  tonto.src = f;
}

我会使用外部JavaScript,将<script>标签放在正文的底部。或者,您可以将 <script> 标记放在<head>中并运行 onload

如注释中所述,HTML 中 id 的目的是针对一个元素。所以我会使用class或新data-TAG.

要将 PHP 脚本也用于其他脚本/站点,我会扫描文件夹并将所有内容转换为 json .(包含 PNG 所有路径的简单数组)

下面是一个使用 JavaScript 1.7(现代 HTML5 浏览器)的示例

使用一个处理程序处理多个元素。

扫描PNG.php

echo json_decode(glob('pano/*.png'));

索引.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
 img{width:100px;}
 img.IMA{opacity:0.3;}
</style>
<script>
var box;
function ajax(a,b,c){c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send()};
function display(){
 box.innerHTML='<img src="'+JSON.parse(this.response).join('"><img src="')+'">';
}
function whatever(e){
 e.target.classList.toggle('IMA');// activate & deactivate
 //or
 //e.target.dataset['IMA']=e.target.dataset['IMA']=='ON'?'OFF':'ON';
}
window.onload=function(){
 box=document.getElementsByTagName('div')[0];
 box.addEventListener('click',whatever,false);
 ajax('scanForPNGs.php',display);
}
</script>
</head>
<body>
<div></div>
</body>
</html>

whatever函数中,您可以向单击的元素添加任何属性或函数。

就我而言,我只是更改不透明度。

触发器是图像本身。

我没有测试这段代码...确保使用Chrome进行测试。

http://jsfiddle.net/8jeDS/1/

谢谢大家和加尔斯。这修复了它:

<?php
            foreach(glob('pano/*.png') as $filename):$path_parts = pathinfo ($filename); $id_front = $path_parts['filename'];?>
                <li> <a onclick = "javascript:chgpano('<?php echo $id_front ?>')"><?php  echo $id_front, "'n";?></a><img id= <?php echo $id_front ?> src= <?php echo$filename ?> style="display:none"></li>
             <?php endforeach; unset( $filename);?>

如您所见,我将用于分配图像 id 的相同变量放入函数参数中。

现在变量 ima 包含 img id

function chgpano(blah)
{
ima = document.getElementById(blah);
init();
}

我必须将变量定义移到div 的

  • 一侧,否则在定义变量之前会填充函数参数。