[英]Remove filepaths from multiple image elements in HTML using jQuery
I'm trying to keep the filenames but remove the filepaths from the image elements on my page, and I've managed to figure out the following based on what I've already gathered from similar questions. 我正在尝试保留文件名,但从页面上的图像元素中删除了文件路径,并且根据已经从类似问题中收集到的内容,我设法找出了以下内容。
I'm able to remove just the filepaths, but I can't figure out why the source of the first image is being copied into the other two images. 我只能删除文件路径,但是我不知道为什么将第一张图片的源复制到其他两张图片中。
Here's what I've put together so far 到目前为止,这是我整理的
HTML 的HTML
<img src="/path/to/image.gif" />
<img src="/different/path/to/picture.jpg" />
<img src="another/path/to/graphic.png" />
JS JS
var abc = $('img').attr('src');
var def = abc.split('/').pop();
$('img').attr('src', def);
RESULT 结果
<img src="image.gif">
<img src="image.gif">
<img src="image.gif">
You arent iterating through all the img elements, try the following: 您不遍历所有img元素,请尝试以下操作:
$('img').each(function(){
var imgName = $(this).attr('src').split('/').pop();
$(this).attr('src', imgName);
});
That way you will loop through all the images and replace accordingly the src attribute. 这样,您将遍历所有图像并相应地替换src属性。
This is how jQuery works. 这就是jQuery的工作方式。 The $ selector grabs an array of items (containing 0-N matched elements) and then applies your operations to those elements.
$选择器获取一组项目(包含0-N个匹配元素),然后将操作应用于这些元素。 For some operations though- read operations like
attr('src')
it only makes sense to read a single item, so it reads the first one. 对于某些操作-读取诸如
attr('src')
,仅读取单个项目才有意义,因此它将读取第一个项目。
What you want is to iterative over the images and apply your regex to them one at a time. 您想要的是遍历图像,然后一次将正则表达式应用于它们。 So...
所以...
$('img').each(function(index, item){
// Read/write attr here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.