我有一个 CFC 通过 AJAX 执行查询,以获取要在我的页面上显示的图像信息/路径列表。在我的表中,我有一个 bool 列 main
指示图像是否是主图像并因此显示在所有其他图像之上。
由于我通过 AJAX 访问查询结果,因此我需要先创建一个数据数组,然后再将其返回到我的 javascript 函数循环返回的数据并构造 <img>
的页面。标签。
如何让我的 CFC 或 javascript 循环识别 main
bool 值并将该图像移动到第一个位置以显示在我的页面上?
这是我的 CFC:
<cfquery name="project_images">
select path, title, alt, main from tbl_images where pid = #projects.pid#;
</cfquery>
<cfloop query="project_images">
<cfset imgStruct = structNew()>
<cfset imgStruct["path"] = path>
<cfset imgStruct["alt"] = alt>
<cfset imgStruct["title"] = title>
<cfset imgStruct["main"] = main>
<cfset ArrayAppend(imgArray, imgStruct)>
</cfloop>
<cfset local.response["images"] = #imgArray#>
<cfreturn local.response>
还有我的 jQuery 函数:
$('.project_class').click(function(e){
e.preventDefault();
var theclass = $(this).attr('id');
var cat = 'planning';
$.getJSON("../cfc/projects.cfc?returnFormat=json&method=getProjects",
{"theclass":theclass, "cat":cat},
function(response){
$('#portfolio_item').html(response.html);
var imageData = response.images;
$.each(imageData, function(i, item) {
$('#portfolio_item').append('<img src="..' + item.path + '" />');
});
});
});
最佳答案
一个选项是在 SQL 中对图像进行排序。使用 CASE
语句为 main
记录分配比其他记录更高的排序顺序。
SELECT CASE WHEN main = 1 THEN 0 ELSE 1 END AS SortNum
, path
, title
, alt
, main
FROM tbl_images
WHERE pid = <cfqueryparam value="#projects.pid#" cfsqltype="cf_sql_integer">
ORDER BY SortNum
或者您可以检查循环中的 main
标志,并在该标志为 true 时使用 arrayPrepend
而不是 arrayAppend
。
关于jquery - 如果 x=true,则将项目移动到 <cfloop> 中的第一个数组位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746251/