Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function to find and replace

Tags:

jquery

I curreny use the following script to find and replace text on my website.

$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Check In", "入住"); });

But there are hundreds of words to find and replace. Some of them share the same CSS path. Can you guys please tell me how to optimise that script and create a function to pass the CSS path and word to find and replace so I can eliminate repetition of the same scripts?

Also is it possible to pass multiple words to find with their replacement text. For an example without writing

$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Room Type", "入住"); });
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Guests", "退房"); });    

Can I do soemthing like

$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace({'Room Type': '房间类型','Guests': '房间类型'}); });

Thanks

like image 749
nasty Avatar asked Nov 13 '15 03:11

nasty


People also ask

How to change text of element in jQuery?

To change text inside an element using jQuery, use the text() method.


1 Answers

You can iterate over an object an replace all the values in it like

var tags = {
  'Room Type': '入住',
  'Guests': '退房'
};
$("#content #tablelabel p").text(function(_, ctx) {
  $.each(tags, function(tag, text) {
    ctx = ctx.replace(tag, text);
  })
  return ctx;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
  <div id="tablelabel">
    <p>Room Type</p>
    <p>Guests</p>
  </div>
</div>
like image 194
Arun P Johny Avatar answered Oct 06 '22 23:10

Arun P Johny