How do I replace instances of a word in multiple tags on page load?

问题: Trying to replace a word that possibly will come in a foreach loop of a database items in razor view. What I've tried so far <section class="section bg-gray">...

问题:

Trying to replace a word that possibly will come in a foreach loop of a database items in razor view.

What I've tried so far

<section class="section bg-gray">
    <div class="container">
        <div class="row gap-y">
            @foreach (var item in Model)
            {
                <div class="col-md-6 col-lg-4">
                    <div class="card d-block">
                        <p class="text-justify">@item.Text</p>
                        <p class="text-center mt-7">
                            <a class="btn btn-primary" href="#">Read more</a>
                        </p>
                    </div>
                </div>
            }
        </div>

        <script src="~/Scripts/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                var elements = getElementsByClassName("text-justify");
                $(elements).each(function(element) {
                    element.innerHTML = element.innerHTML.replace(/wordToReplace/g, 'newWord');
                });
            });
        </script>
    </div>
</section>

Excuse my poor JavaScript, I'm new on front-end. I looked for similar questions but closer topics are usually about replacing instances of a word in one tag. Please help.


回答1:

You don't need jQuery for this - you can use document.querySelectorAll and just replace the desired text of the elements that match the selector.

Note that I have dodgied up a text element and for the desired class and replacing justify with justified to demonstrate the usage.

let elements = document.querySelectorAll(".text-justify");

elements.forEach(function(element){
  let textContent = element.innerText;
  let newTextContent = textContent.replace(/justify/g, 'justified');
  element.innerText = newTextContent;
})
<p class="text-justify">This is a text with the class of text-justify</p>
<p>This is a text without the class of text-justify</p>
<p class="text-justify">This is a text with the class of text-justify</p>


回答2:

You don't need jQuery for this - use a simple forEach loop. I've also refactored some other parts of your code (eg you were missing document:

document.getElementsByClassName("text-justify").forEach(element => element.innerHTML = element.innerHTML.replace(/word/g, "newWord"));

But if you really want to use jQuery:

$(".text-justify").html((index, element) => element.replace(/word/g, "newWord"));
  • 发表于 2019-02-18 16:39
  • 阅读 ( 209 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除