如何将副本与括号匹配 Javascript

问题描述

我正在尝试在页面上查找特定的产品名称,如果匹配,那么我想在该名称的末尾添加“- 10% 折扣”。

我遇到的问题是在括号“(1+1)”中的产品名称末尾我如何将其包含在变量 findCopy 中,因此我的结果将是:“产品名称(1 +1) - 10% 折扣"

var findCopy = 'Product Name';
// The below is what I'm trying to achieve to get
// var findCopy = 'Product Name (1+1)';
var targetThis = document.querySelector('.copy');
targetThis.innerText = targetThis.textContent.replace(new RegExp(findCopy),findCopy + '  - 10% Discount');
<p class="copy">Product Name (1+1)</p>

解决方法

您知道产品名称如 Product Name (1+1),因此您需要找到具有相同值的标签,然后将其附加 - 10% Discount

var findCopy = 'Product Name (1+1)';
        // The below is what I'm trying to achieve to get
        // var findCopy = 'Product Name (1+1)';
var targetThis = [...document.querySelectorAll('.copy')].filter(tag => tag.textContent.includes(findCopy))[0] 

targetThis.innerText = targetThis.textContent + '  - 10% Discount';
    <p class="copy">Product Name (1+1)</p>

无扩展运算符的更新

        var findCopy = 'Product Name (1+1)';
        // The below is what I'm trying to achieve to get
        // var findCopy = 'Product Name (1+1)';

        var array = document.querySelectorAll('.copy');
        var targetThis;
        for (var i = 0; i < array.length; i++) {
            if (array[i].textContent.includes(findCopy))
                targetThis = array[i];
        }


        targetThis.innerText = targetThis.textContent + '  - 10% Discount';
 <p class="copy">Product Name (1+1)</p>

,

主要基于 Alireza Ahmadi 解决方案,但允许您一次更改多个产品:

@click="async () => { await getImage(image.id); toggleWindow();}"
var findCopy = 'Product Name';
        // The below is what I'm trying to achieve to get
        // var findCopy = 'Product Name (1+1)';
var targetThis = [...document.querySelectorAll('.copy')].filter(tag => tag.textContent.includes(findCopy))

targetThis.forEach(el => el.innerText = el.textContent + '  - 10% Discount');

,

我不知道你是否可以使用jQuery。在这里,我使用 jQuery 做了一个解决方案。当然它适用于多个

并将它们全部更改

HTML:

<div class="new">
        <p>
            product Name 1
        </p>
        <p>
            product Name 2
        </p>
        <p>
            product Name 3
        </p>
        <p>
            product Name 1 abcde
        </p>
    </div>
<button onclick="test('product Name 1')">test</button>

JS代码:

function test(string) {         
                $("p:contains('" + string + "')").each(function () {
                    var sHtml = $(this).html();
                    $(this).html(sHtml + " - 10% Discount");
                })
        }

最后它会改变如下内容:

产品名称 1 - 10% 折扣

产品名称 2

产品名称 3

产品名称 1 abcde - 10% 折扣

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...