我有一个输入搜索字段,我在其中按名称过滤图像并显示包含所写名称或部分名称的图像。
但现在我也想通过属性 alt
添加搜索。因此要按名称和标签显示过滤后的图像。
<input type="text" id="inputValue" placeholder="Type to search"></input>
<button onclick="Images()" type="button">SEARCH</button>
<div class="imgBox"><img id="image_id_009"
src="Photos/20130610_171751.jpg" alt="track">
<p>Title009</p>
</div>
<div class="imgBox"><img id="image_id_009"
src="Photos/20130610_171751.jpg" alt="carting">
<p>Title009</p>
</div>
<div class="imgBox"><img id="image_id_009"
src="Photos/20130610_171751.jpg" alt="driver">
<p>Title009</p>
</div>
JavaScript:
function Images(){
let filtering=$("#inputValue").val().toLowerCase();
$(".Box").hide();
$('.Box').each(function(){
if ($(this).text().toLowerCase().indexOf(filtering) !== -1) {
$(this).show();
}
});
};
最佳答案
您只需添加||即可$("img", this).attr("alt").toLowerCase().indexOf(filtering) !== -1
到您现有的 if 语句
function Images() {
let filtering = $("#inputValue").val().toLowerCase();
$(".imgBox").hide();
$('.imgBox').each(function() {
if ($(this).text().toLowerCase().indexOf(filtering) !== -1 || $("img", this).attr("alt").toLowerCase().indexOf(filtering) !== -1) {
$(this).show();
}
});
};
注意我已将 $('.Box')
更改为 $('.imgBox')
以使示例正常工作
演示
function Images() {
let filtering = $("#inputValue").val().toLowerCase();
$(".imgBox").hide();
$('.imgBox').each(function() {
if ($(this).text().toLowerCase().indexOf(filtering) !== -1 || $("img", this).attr("alt").toLowerCase().indexOf(filtering) !== -1) {
$(this).show();
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inputValue" placeholder="Type to search"></input>
<button onclick="Images()" type="button">SEARCH</button>
<div class="imgBox"><img id="image_id_009" src="Photos/20130610_171751.jpg" alt="track">
<p>Title009</p>
</div>
<div class="imgBox"><img id="image_id_009" src="Photos/20130610_171751.jpg" alt="carting">
<p>Title009</p>
</div>
<div class="imgBox"><img id="image_id_009" src="Photos/20130610_171751.jpg" alt="driver">
<p>Title009</p>
</div>
关于javascript - 如何创建 <input> 搜索字段,通过 html alt 属性查找图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732778/