我有一个javascript数组,我想用jstl为每个迭代它们并显示输出。
<script type="text/javascript">
phoneFilterObject = {
allPhoneArray: []
}
var specPhone = [];
OnUserSelect(){
//loop through allPhoneArray
//do filtering logic and populate specPhone array
}
</script>
<body>
// here I want to iterate through the specPhone array and display it. also I want to populate hidden variables with values from specPhoneArray
// i want to do the following
<c:if test="${!empty specPhoneArray}">
<c:foreach items="${specPhoneArray}" var="phoneObj">
<c:out value="${phoneObj.name}"/>
<input type="hidden" name="phoneID" value="<c:out value='${phoneObj.id}'/>"/>
</c:foreach>
</c:if>
</body>
我无法在jquery中读取javascript数组。我尝试了以下
specPhoneArray = $(specPhoneArray); &
specPhoneArray = ${specPhoneArray};
this.specPhoneArray = $(specPhoneArray);
感谢任何帮助。
答案 0 :(得分:0)
你不能用JSTL做到这一点,但你可以通过保持JavaScript世界来实现它。首先创建一个模板并将其添加到您的页面:
<script id="phone-tmpl" type="text/html">
{name}
<input type="hidden" name="phoneID" value="{id}"/>
</script>
然后在JavaScript中添加一个小模板助手:
function t(s,d) {
for (var p in d) {
s = s.replace(new RegExp('{'+p+'}','g'), d[p]);
}
return s;
}
然后你可以做(假设你正在使用jQuery):
var phoneTmpl = $('#phone-tmpl').html(),
html = "";
for (var i = 0, l = specPhone.length; i < l; i++) {
html += t(phoneTmpl, specPhone[i]);
}
// do something with html
$('body').append(html);
您还可以查看此演示:http://jsfiddle.net/d5jaY/