签出这个
working example
:)
window.onload = ()=>{
// get our form
let imageForm = document.getElementById('image-form');
// something to inform us that the form has been submitted
imageForm.addEventListener('submit', function(){
console.log(`form data: ${$(this).serialize()}`);
});
// get all the img elements
let images = document.querySelectorAll('img');
// get the input field where we'll be putting the total image count
let field = document.getElementById('image-count');
// the number of images that match our criteria
let imageCount = 0;
// count the number of img elements that have 'test.png' as their source
for(let i = 0; i < images.length; i++){
if(images[i].getAttribute('src') === 'test.png'){
imageCount++;
}
}
// set the image count (imageCount) as the value of the text field
field.value = imageCount;
// submit the form
imageForm.dispatchEvent(new Event('submit'));
};
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<form id="image-form" name="imageCount">
<img src="test.png" class="img-1">
<img src="test.png" class="img-1">
<img src="test.png" class="img-1">
<img src="test.png" class="img-1">
<img src="test.png" class="img-1">
<img src="test.png" class="img-1">
<img src="test.png" class="img-1">
<img src="exclude.png" class="img-2">
<img src="exclude.png" class="img-2">
<img src="exclude.png" class="img-2">
<img src="exclude.png" class="img-2">
<img src="exclude.png" class="img-2">
<input type="text" id="image-count" name="imageWithSourceCount">
</form>
考虑到以下HTML,还有一件事:
<img src="images/test.png" class="img-1">
src公司
图像对象的属性(
img.src
),您将得到解析的路径
yourwebsite.com/images/test.png
获取属性
img.getAttribute('src')
),您将得到
src
属性,也可以是相对路径(即。
images/test.png