简体   繁体   中英

If else javascript statement

I have a code that i want to execute but dont know how to go about it. I have a page that you can convert between two languages, english and french. I want to run a script in my index.html.erb file only if the page is in french and not in English.

This code is at the beginning of my index.html.erb file.

<script>
  var a = <%= params[:locale]%>
  if(a == "fr")
  {
   <script type="text/javascript">
    /* <![CDATA[ */
    var google_conversion_id = 1001007867;
    /* ]]> */
  </script>
  <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
  </script>
  <noscript>
    <div style="display:inline;">
    </div>
  </noscript>
}
</script>

I am not sure if my code is correct. Any help is appreciated.

you cant nest script tags, you could append a script tag if your condition is met, sth. like :

<script>
var a = <%= params[:locale]%>;
console.log(a) /* THIS REALLY LOGS THE EXPECTED VALUE ? */
if(a == "fr")
{
     var google_conversion_id = 1001007867;
     var bh = document.createElement('script'), s = document.getElementsByTagName('script')[0];
     bh.type = 'text/javascript';
     bh.src = '//www.googleadservices.com/pagead/conversion.js';
     s.parentNode.insertBefore(bh, s);

}
</script>
  <noscript>
    <div style="display:inline;">
    </div>
  </noscript>

the better solutions would be if your templating-language eg <%= %> supports if else conditions

check your browser console for errors

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