简体   繁体   中英

jQuery: Using replaceWith function

I want to replace a jQuery function in side script tag. I have this jQuery function in my layout just before the </body> tag.

<div id="white_backstretch">
  <script>
     $.backstretch("/body-bg.jpg");
  </script>
</div>

On another page (show page) I have:

<script>
  $('#white_backstretch').replaceWith("<script>" + $.backstretch(<%= @white_label.logo %> + "</script>");
</script>

Here I am trying to replace the existing

<script>$.backstretch("/body-bg.jpg");</script>

with

<script>$.backstretch(<%= @profile.logo %></script>

so that when different page come the background image will change. But the problem I am facing is:

<script>
  $('#white_backstretch').replaceWith("<script>" +     $.backstretch(/uploads/white/logo/4/image14.png) + "</script>");

Uncaught SyntaxError: Unexpected token ILLEGAL

First end </script> tag inside replace function is taken as end of the script so ");" <-- thrown as unexpected token error

So, it will be help full if any one tell me how to replace a jQuery method inside a script tag with another jQuery method? (this method should also be inside script tag since I want to use replaceWith jQuery method inside a html file)

$.replaceWith will just replace and not execute the javascript. Even if you are able to get it working, it will be of no use.

I suggest you do this another way, by using function overriding

<div id="white_backstretch">
  <script>
      function replace() {
          $.backstretch("/body-bg.jpg");
      }         
  </script>
</div>

And in your show page

document.write("<script>function replace(){$.backstretch("<%= @profile.logo %>");} </script>")

and call replace() in page load or whereever it is appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM