根据"alt"标签键入时过滤图像



我需要根据"alt"属性中包含的文本,动态地仅显示包含输入字段中键入的文本的图像。

我也需要一些特殊字符过滤器,并且对键入的文本不区分大小写。例如,当键入单词"coração"时,带有"coracao"的图像必须显示在结果中,并且还要忽略大小写("CORAÇÃO"必须返回带有"coracao"的图像,或者"example"必须返回"example"(。请记住,alt 属性不会包含任何特殊字符。

我有的代码是(我不知道javascript,只是在互联网上找到(

$("#myinput").keyup(function() {
var val = $.trim(this.value);
if (val === "")
$('img').show();
else {
$('img').hide();
$('img[alt*=' + val + "]").show();
}
});

谢谢。

这是您在小提琴中的工作代码,我很快就会向您发送特殊字符的过滤器!

<img src="http://via.placeholder.com/160x80" alt="16">
<img src="http://via.placeholder.com/150x80" alt="15">
<img src="http://via.placeholder.com/140x80" alt="14">
<img src="http://via.placeholder.com/130x80" alt="13">
<input type="text" id="filter">
$("#filter").keyup(function() {
var val = $.trim(this.value);
if (val === "")
$('img').show();
else {
$('img').hide();
$('img[alt*=' + val + "]").show();
}
});

更新:带有特殊字符的新小提琴!

这似乎可以做你想要的。请注意,这仅适用于 ES6(这意味着更新的浏览器 - 可能不亚于 Internet Explorer 11(。按照此答案的建议,使用String.Prototype.Normalize()去除特殊字符。

$('#myinput').keyup(function() {
let val = $.trim(this.value);
val = val.normalize('NFD').replace(/[u0300-u036f]/g, '');
if (val === '') {
$('img').show();
} else {
$('img').hide();
$('img').each((i, img) => {
let imgAlt = img.alt.normalize('NFD').replace(/[u0300-u036f]/g, '');
if((imgAlt.toLowerCase()).indexOf(val.toLowerCase()) > -1) {
$(img).show();
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myinput">
<img alt="CORAÇÃO">
<img alt="CORACAO">
<img alt="foo">
<img alt="bar">
<img alt="baz">

所以你想要的是删除特殊字符,但保留相关的字母。

可以使用字符串规范化方法,然后删除不需要的字符:

function removeDiacritics(str) {
return str && str.normalize('NFD').replace(/[u0300-u036f]/g, '');
}
removeDiacritics('Coração'); // Coracao

更新

要使其在您的代码中工作,请执行以下操作:

$(function() {
function removeDiacritics(str) {
return str && str.normalize('NFD').replace(/[u0300-u036f]/g, '');
}
function normalize(str) {
return (removeDiacritics(str) || '').trim().toLowerCase();
}
$("#myinput").keyup(function() {
var val = normalize(this.value);
if (val === "")
$('img').show();
else {
$('img').hide();
// assuming the alt is already normalized
$('img[alt*=' + val + "]").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- You can enter words with special characters in the input, like CORAÇÃO -->
<input id="myinput">
<img alt="coracao">
<img alt="construcao">
<img alt="automovel">
<img alt="estacao">

您可以在上面的代码片段中看到 html 和 js 代码。

最新更新