doucheng5209 2013-12-16 11:38
浏览 58
已采纳

在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>";
  • 写回答

2条回答 默认 最新

  • drdzpknk76046 2013-12-16 12:05
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类