我正在尝试在页面加载上创建一个图像审查功能。
- 在页面加载时扫描某些类元素的值
- 如果几个元素的值超过5
- 将img src更改为一个值计数超过5
我想在阅读了stackoverflow中的其他问题后,我知道了如何扫描和更改,但我不能只更改特定的问题。
据我所知,以下代码将在扫描单个6 时审查所有图像
例如:HTML
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="naked_image.jpg"><p class="report-count">6</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
javascript
$(document).ready(function () {
var count = $('.report-count').val();
if (count > 5 ) {
$('.showing-image').attr('src', 'censored.jgp');
}
});
请帮助
您可以使用filter()
:
$(document).ready(function () {
$('.report-count')
.filter((i, node) => +node.textContent > 5)
.prev()
.attr("src", 'censored.jpg');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="naked_image.jpg"><p class="report-count">6</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
同样的东西,但使用香草javascript(又称更快(:
document.addEventListener("DOMContentLoaded", e =>
{
const report = document.querySelectorAll(".report-count");
for(let i = 0; i < report.length; i++)
{
if (+report[i].textContent > 5)
{
report[i].previousSibling.src = 'censored.jpg';
/* use this line instead if img and p.report-count are not next to each other, but they have common parent */
//report[i].parentNode.querySelector("img.showing-image").src = 'censored.jgp';
}
}
});
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="naked_image.jpg"><p class="report-count">6</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
如果img
和.report-count
不是同级:
document.addEventListener("DOMContentLoaded", () =>
{
const box = document.querySelectorAll(".auto-listed-box");
for(let i = 0; i < box.length; i++)
{
if (+box[i].querySelector(".report-count").textContent > 5)
{
box[i].querySelector("img.showing-image").src = 'censored.jpg';
}
}
});
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="naked_image.jpg"><p class="report-count">6</p>
</div>
<div class="auto-listed-box">
<img class="showing-image" src="normal_image.jpg"><p class="report-count">0</p>
</div>