在PHP循环中动态创建jQuery listview

I would like to populate a jQuery listview in a PHP loop, and I attempted to do so by echoing javascript code that populates the list with a PHP variable. This is what I'm working with:

My HTML

<div data-role='page' id='feedPage'>
     <div data-role='content'>
        <ul id='pics' data-role='listview'>
        <li>test</li>
        </ul>
     </div>
</div>

and my PHP / JavaScript

echo "<script type='javascript'>
var pics = \$('#pics')
var pitem = \$('<li/>').html($myArray[element])
var plink = \$('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
</script>";

but the list comes up blank. This code is running inside of a PHP for loop, and I am able to access and manipulate all the elements of $myArray just fine in PHP, but I cannot seem to populate the list. I even tried running this code with a simple .html('hello') to no avail. All I get is a blank list with the exception of the test item I hardcoded in the HTML. Is there a way to generate a list in PHP like this, and if so, how can I do it properly?

Thanks!

SOLUTION:

I got this working simply by doing <script type='text/javascript'> and .html('$myArray[element]') (notice the single quotes). This works because the javascript is running inside a PHP echo. Oh, and none of my $ needed to be escaped. Final code:

echo "<script type='text/javascript'>
var pics = $('#pics')
var pitem = $('<li/>').html('$myArray[element]')
var plink = $('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
</script>";

I think the main problem is in type='javascript', it should be type='text/javascript'.

Another thing to consider is that the content of the $myArray[element] needs to be printed as a javascript string. Running $myArray = array_map('json_encode', $myArray); should do the trick.

You forgot to put your JS-code into document.ready event callback

$(document).ready(function($){
  var pics = $('#pics')
  var pitem = $('<li/>').html($myArray[element])
  var plink = $('<a/>')
  pitem.append(plink)
  pics.append(pitem)
  pics.listview('refresh')
});