Javascript ID groupings

Javascript ID groupings

本文关键字:groupings ID Javascript      更新时间:2023-09-26

我希望创建一个例外,该异常根据其.php ID号创建2个组。

我目前有一个填写图像表的表单,并希望使用 javascript 将它们分成几组。

当前脚本如下所示:

var currentResults;
function init() {
getProducts();}
function getProducts() {
$.ajax({
    url:"php/products.php",
    dataType: "json",
    data: { public: true },
    success:function(result){
        processResults(result);
    }
});}
function processResults(results) {
currentResults = null;
if (!results && !results.products) 
    return; 
currentResults = results.products;
for (var i = 0; i < results.products.length; i++) {
    processResult(results.products[i]);}
$(".galleryitem").click(handleThumbnailClick);}
function processResult(result) {
    var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
    newDiv += '<div class="imageHover" style="background: ' + result.color + '">&nbsp;</div>';
    newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if (result.artist)
    newDiv +=   '<div class="imageArtist">' + result.artist + '</div>';
    newDiv += '</div>';
$('#gallery').append(newDiv);}
function handleThumbnailClick(e) {
    if (!e || !e.currentTarget || !e.currentTarget.id)
    return;
    var id = e.currentTarget.id.substring(11);
window.location = 'product.php?id=' + id;}
function encodeImagePath(path) {
return path.replace(/#/g, '%23');}

我正在寻找一些关于如何根据产品的 ID 号将其拆分为多个div 的简单建议,以一次使用不同的标题文本执行 6 张图像的部分。

请指教!! 非常感谢!

不确定我是否正确理解了您的想法,但这样的事情应该可以解决您的问题(如果您在从服务器获得的产品 JSON 中具有"父"属性):

function processResult(result) {
    if (typeof(result.parent) !== 'undefined') { // see if the element has a parent
        var newDiv = 'markup goes here'; // if some of the markup would be reused you can create a new function for this
        $('#galleryitem' + result.parent).append(newDiv); // just make sure the parent is already there
    } else {
        var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">'; // default behavior that you alreay had
        // code skipped for brevity
        $('#gallery').append(newDiv);
    }
}

附言你应该处理你的代码格式 - 如果格式正确,它可以更容易阅读。