简体   繁体   中英

How to pass a string value dynamically to a <div>(html)?

In the html.erb file of rails app, I have a html element. I want to pass the id to this div at run time. How can I achieve this? The below method does not work.

<script type="text/javascript">
var s = 'SkypeButton_Call_' + 'dsdsaf'+ '_1'
<div id=s></div>
 </script>`

Thanks

If you have a div in an html.erb file, then you can simply define that id like so:

<div id='SkypeButton_Call_dsdsaf_1'></div>

Please reply if this is not what you are looking for. Are you looking to work off of a ruby variable from your Rails controller?

If you have a ruby variable:

@my_var = 'dsdsaf'

Then you could do something like this:

<div id="<%= @my_var %>"></div>

You may put your div inside another div with an class identifier:

<div class='parent'> 
  <div></div> 
</div>

And then, by using jquery you could do something like this:

<script type="text/javascript">
  var s = 'SkypeButton_Call_' + 'dsdsaf'+ '_1';
  $(document).ready(function () {
    var child = $( ".parent" ).find("div"); //This var holds the child div of .parent
    child.attr("id", s); //This line sets id=s in the child div
  });
</script>

The result should be:

<div class='parent'>
  <div id='SkypeButton_Call_dsdsaf_1'></div>
</div>

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