开发者

trying to add variable for div id. is it possible?

i am trying to use variable inside body. just see below sample code

<body>
 <div class="demo">
     <script>
     var count = 4;
      for(i=1;i<=count;i++){
          var varSlid = "A"+i;
          $('.demo').append('<div id= varSlid ></div></br>');
      }
     </script>
</div>
</body>

but it is throwing errors. ple开发者_JAVA技巧ase check and tell me where the error is?


Try This

var varSlid = "A"+i;
          $('.demo').append('<div id= ' + varSlid  + '></div></br>');


The error is that .demo hasn't finished parsing yet, so you shouldn't be attempting to manipulate it. This can cause serious issues in older versions of IE ("operation aborted", anyone?). Move the script to just outside the <div> tag:

<body>
<div class="demo">
</div>
<script>
     var count = 4;
      for(var i=1;i<=count;i++){
          var varSlid = "A"+i;
          $('.demo').append('<div id='+varSlid+'></div><br/>');
      }
</script>
</body>

As others have pointed out, you also need the quotation marks to work the variable into your HTML string, although this wouldn't have caused any errors - you would just end up with a bunch of elements all with the same id ("varSlid").


Maybe it's my lack of jQuery-fu... but shouldn't </br> be <br/>?

Also, you shouldn't create 4 elements <div id= varSlid > since the id attribute should be unique.

Edit: You probably intended to use the value of the variable varSlid as the id attribute, but rit now it's part of a hardcoded string literal. You'd want to something more like:

$('.demo').append('<div id="'+varSlid+"'></div><br/>');


Try this...

$('.demo').append($('div').attr('id', varSlid)).append('<br/>');

Also wrap this entire function in on dom ready like

$(function(){
    //your code here...
});


change: $('.demo').append('<div id= varSlid ></div></br>'); to: $('.demo').append('<div id=' + varSlid + ' ></div></br>');


It's : $('.demo').append('<div id="' + varSlid + '"></div></br>');


I'm not real clear on the OP's original question, but this fits the title.

HTML5 has a data-* attribute, where the * represents your data. I've had luck with this passing Web.py (python) variables from the templator to js functions.

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

<!DOCTYPE html> <!--declare we are using HTML5-->
<html>
<head>
  <script>
    var jsVersionData = ''; //create a global variable for example simplicity
  </script>
</head>
<body>
  <div id="stored-variable" data-stored="7">
    <script> 
      jsVersonData =  document.getElementById("stored-variable");  //get the variable from the div
    </script>  
  </div>

  <script>
    var myStr = jsVersonData.dataset.stored;  // the variable
    var myInt = Number(myStr);                // convert the variable to int
    alert(myInt + 1);
  </script>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜