1

在某人的帮助下,我创建了一个在页面中加载 JSON 内容的脚本。问题是内容被加载了太多次而不是一次。这是 jquery 函数,它包含在页面头部的 main.js 文件中:

    function bakVorm(page,targetClass)
     {
     $.getJSON('http://shop.com/'+page+'/?format=json', function(data){
      var text = ''
      $.each(data.textpage, function(index, text){
      $(text).html('' + text + '').appendTo(targetClass);
});
});

在产品页面上,我尝试使用以下代码将内容加载到 div 中:

$(function(){
bakVorm('vraag','.eigenschappen');
bakVorm('test','.verzendkosten');
});

问题是内容在相应的div中加载了太多次。可能脚本没有停止或其他什么。

欢迎任何帮助

4

2 回答 2

2

在这一行

$(text).html('' + text + '').appendTo(targetClass);

您正在将文本的内容添加到文本中的每个顶级节点,所以如果文本是

 <div></div><p></p>

你最终会得到

<div><div></div><p></p></div><p><div></div><p></p></p>

所以省略 html 部分,只需要

$(text).appendTo(targetClass);
于 2012-05-28T18:07:29.123 回答
0

尝试清空代码中的 targetClass:

function bakVorm(page,targetClass)
 {
 $.getJSON('http://shop.com/'+page+'/?format=json', function(data){
  var text = ''
  $.each(data.textpage, function(index, text){
  $(targetClass).empty().append(text);
  });
});

或者尝试不使用append

function bakVorm(page,targetClass)
 {
 $.getJSON('http://shop.com/'+page+'/?format=json', function(data){
  var text = ''
  $.each(data.textpage, function(index, text){
  $(targetClass).html(text);
  });
});
于 2012-05-28T17:46:12.273 回答