1

所以我有这个从 php 文件中提取 JSON 的 JS 代码。这样可行。我要做的是在将 JSON 值放入 DOM 之前更改 JSON 值,以用较低分辨率的图像替换图像 URL。您将在调用mobile()函数的 IF 语句中看到它的开头

开始了:

$.post(url, project, function(data, textStatus) {
  $(data.tags).each(function(i, item){
    projectTags += "<span class='project-tag'>"+item+"</span>";
  });

  $(data.slides).each(function(i, item){

    if ((mobile() == true && $(window).width() <= 680)){
      if (i != 0){
        console.log('Before' +item);
        var newItem = JSON.stringify(item);
        $(newItem).replace('.png','-lofi.png');
        console.log(newItem);

        console.log('After' + item);
      }
    }

    projectImages += "<div class=\"slide-container\">" + item + "</div>";
    console.log(projectImages);
  });
  setTimeout(function(){
    btnAbout.removeClass('active');
    sectionDetail
      .attr('data-id', data.id)
      .find('.project-name').html(data.name).end()
      .find('.project-year').html(data.year).end()
      .find('.project-agency').html(data.agency).end()
      .find('.project-details').html(data.details).end()
      .find('.project-tags').html(projectTags).end()
      .find('#slideshow').html(projectImages);
}, "json");

是什么赋予了?如果它是比 iPad 小的移动设备,我想要做的就是替换 JSON 值的 URL。

编辑:由詹姆斯修复!谢谢,兄弟!最终代码如下。

$.post(url, project, function(data, textStatus) {
  $(data.tags).each(function(i, item){
    projectTags += "<span class='project-tag'>"+item+"</span>";
  });

  $(data.slides).each(function(i, item){
    var loFi = JSON.stringify(item);
    if ((mobile() == true && $(window).width() <= 680)){
      if (i != 0){
        loFi = loFi.replace(/(.png)/g,'-lofi.png')
        loFi = $.parseJSON(loFi);
        item = loFi;
      }
    }
    projectImages += "<div class=\"slide-container\">" + item + "</div>";

  });
  setTimeout(function(){
    btnAbout.removeClass('active');
    sectionDetail
      .attr('data-id', data.id)
      .find('.project-name').html(data.name).end()
      .find('.project-year').html(data.year).end()
      .find('.project-agency').html(data.agency).end()
      .find('.project-details').html(data.details).end()
      .find('.project-tags').html(projectTags).end()
      .find('#slideshow').html(projectImages);
}, "json");
4

2 回答 2

2

应该:

var newItem = JSON.stringify(item);
newItem = newItem.replace('.png','-lofi.png');

您忘记将“替换”的结果分配给您的变量,并且您不需要将 newItem 包装在 $(..) 中,replace 是一个String对象函数。

PS。你可能也不需要stringify。你的物品不是已经是字符串了吗?

于 2013-07-24T04:29:29.350 回答
1
$(data.slides).each(function(i, item){

var newItem = JSON.stringify(item);  <-- Add this early

if ((mobile() == true && $(window).width() <= 680)){
  if (i != 0){
    console.log('Before' +item);
    newItem = newItem.replace(/(.png)/g,'-lofi.png');
    console.log(newItem);

    console.log('After' + item);
  }
}

您还在此处添加常规项目吗?您对项目所做的任何更改都不会反映。

projectImages += "<div class=\"slide-container\">" + item + "</div>";

改成

projectImages += "<div class=\"slide-container\">" + newItem + "</div>";
于 2013-07-24T04:20:04.753 回答