【问题标题】:Javascript ID groupingsJavascript ID 分组
【发布时间】:2014-12-14 18:16:57
【问题描述】:

我正在寻找一个例外,它根据他们的 .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 个图像的部分。

请指教!!非常感谢!

【问题讨论】:

  • 您不需要在每次将 div 添加到#gallery 时都附加点击事件。只需使用一次$('#gallery').on("click", ".galleryitem", function(){/*some code*/});
  • “基于 ID”到底是什么意思? DB中的自动递增字段并不总是意味着它递增+1。例如,在 3 个服务器的集群上,它将是 +1、+2 或 +3,具体取决于处理插入查询的服务器。

标签: javascript php gallery grouping


【解决方案1】:

不确定我的想法是否正确,但这样的事情应该可以解决您的问题(如果您从服务器获取的产品 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);
    }
}

附:你应该处理你的代码格式——如果格式正确,它会更容易阅读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2021-10-14
    相关资源
    最近更新 更多