这听起来可能是个愚蠢的问题。 我在页面内有一组图像。 而这些图像没有ID但只有一个类。 我希望通过类名获取这些元素,并用不同的内容替换它们。 我该怎么做
This may sound a dumb question. I have a set of images inside a page. And these images doesnt have an ID but a class. I want to get these elements by their class names and replace each of them with different content. How should I do that.
最满意答案
以下使用vanilla JavaScript(没有jQuery)并且:
在页面中选择已分配类的图像(在此示例中为imageClass )。 document.querySelectorAll()允许您使用CSS3选择器来选择DOM元素。
更改每个图像(src链接)的“内容”,以便您可以显示不同的图像。
单击示例中的按钮可更改图像的“内容”。
(function() { var changeContent = function() { document.querySelectorAll('.imageClass').forEach(function(image) { image.src = 'https://placeimg.com/340/280/people' }); }; document.getElementById('btn').addEventListener('click', changeContent); })();<button id="btn" type="button">Change Images</button> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals">The following using vanilla JavaScript (no jQuery) and does:
Select images in your page which have a class assigned (in this example imageClass). The document.querySelectorAll() allows you to select DOM elements using CSS3 selectors.
Change "content" for each image (src link), so yo ucan show up different images.
Click the button in the example to change "content" for images.
(function() { var changeContent = function() { document.querySelectorAll('.imageClass').forEach(function(image) { image.src = 'https://placeimg.com/340/280/people' }); }; document.getElementById('btn').addEventListener('click', changeContent); })();<button id="btn" type="button">Change Images</button> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals">
更多推荐
发布评论