我正在尝试为从数据库返回的一些图像设置 id 属性
id 属性仅适用于用户单击的图像。
我的问题是我有重复的图像,很难区分不同的图像。
我将单击的图像存储src
到数据库中以识别哪个图像应该具有 id 属性。
当用户单击图像时,ID 将自动生成。
我的html就像
<div>
<img src='test1.jpg'/>
<img src='test1.jpg'/>
<img src='test1.jpg'/>
<img src='test2.jpg'/>
<img src='test3.jpg'/>
</div>
在 php 中渲染图像
$html is the string that are returning from DB. it has all kind of html tags.
$doc = new DOMDocument();
@$doc->loadHTML($html);
$imageTags = $doc->getElementsByTagName('img');
$imgSource is the array of images that are supposed to have id attribute
$imgID is the array of ids for the images that were clicked
$source is the current image taht are being checked
foreach($imageTags as $tag) {
$source=$tag->getAttribute('src');
if(in_array($source, $imgSource)){
$ids=array_keys($imgSource,$source);
foreach($ids as $id){
$tag->setAttribute('id',$imgID[$id]);
$htmlString=$doc->saveHTML();
}
}
}
test1
如果用户点击和test2
图像,我上面的代码将生成如下所示的 html
<div>
<img id='123' src='test1.jpg'/>
<img id='123' src='test1.jpg'/>
<img id='123' src='test1.jpg'/>
<img id='456' src='test2.jpg'/>
<img src='test3.jpg'/>
</div>
id
123适用于所有人test1.jpg
,这不是我想要的。我试图通过查找图像位置索引来避免这个问题。因此,如果用户单击第二个test1.jpg
,则索引将为 2。如果用户单击第三个test1.jpg
,则索引将为 3。
但是,我不确定如何将其应用于我的 php 代码。我当时只能更改php中的代码。任何人都可以帮助我吗?非常感谢!