javascript - 怎么做搜索字段,它通过 html alt 属性找到图像
问题描述
我有一个输入搜索字段,我已在其中按名称过滤图像并显示包含所写名称或部分名称的图像。但现在我也想将搜索添加为按属性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 statement
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>
推荐阅读
- java - Java 中的 AVX/AVX2 支持,没有 JNI 开销
- c++ - 如何将 std::sqrt 作为参数传递
- r - 通过 R 中的另一个对象变量对变量重新排序
- flutter - 发生异常:类型'MappedListIterable
' 不是类型 'List 的子类型 ' stackTrace: #0 new GenreResponse.fromJson - dart - 为什么可选参数的默认值必须是常量?
- html - html 'step' 属性不再起作用了吗?
- jekyll - Jekyll 链接缺少 Baseurl
- flutter - UserProfile 在 auth.getCurrentUser() 之后崩溃
- c# - TFVC 以编程方式获取特定日期时间版本的项目
- protocol-buffers - 相当于 JWK 的 Protobuf