jQuery 将 HTML 添加到包含多个关键字的链接

问题描述 投票:0回答:1

我有几个链接,我想根据找到的链接中的字符串附加单词“SALE”,我已经成功使用了下面的代码。但是,如果可能的话,我希望能够让代码查看多个字符串。

目前,“SALE”一词附加到包含字符串“SHIRT”的链接。我也希望它也适用于所有包含“JACKET”的链接。

有没有办法把它作为一个数组来做?

<div>
    <div class="link"><a href="/products/WHITESHIRT">White Shirt</a></div>
    <div class="link"><a href="/products/BLACKSHIRT">Black Shirt</a></div>
    <div class="link"><a href="/products/GREENSHIRT">Green Shirt</a></div>
    <div class="link"><a href="/products/WHITESHORTS">White Shorts</a></div>
    <div class="link"><a href="/products/BLACKTROUSERS">Black Trousers</a></div>
    <div class="link"><a href="/products/YELLOWJACKET">Yellow Jacket</a></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
<script>
$(".link a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('SHIRT') > -1) {
    $(this).append(" SALE");
    }
});
</script>   
jquery string indexof
1个回答
0
投票

这里可以使用数组

some
方法

阵列
some

array.some(function(value, index, arr), this)

尝试下面的代码

var keywords = ['SHIRT', 'JACKET'];
$(".link a").each(function () {
    var href = $(this).prop('href');
    if (keywords.some(function (v) { return href.indexOf(v) >= 0; })) {
        $(this).append(" SALE");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <div class="link"><a href="/products/WHITESHIRT">White Shirt</a></div>
    <div class="link"><a href="/products/BLACKSHIRT">Black Shirt</a></div>
    <div class="link"><a href="/products/GREENSHIRT">Green Shirt</a></div>
    <div class="link"><a href="/products/WHITESHORTS">White Shorts</a></div>
    <div class="link"><a href="/products/BLACKTROUSERS">Black Trousers</a></div>
    <div class="link"><a href="/products/YELLOWJACKET">Yellow Jacket</a></div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.