duan0417 2012-12-17 19:01
浏览 22
已采纳

为什么我的JQuery脚本在追加时添加了html标签?

I have a problem when sending a json array to my jquery script where I want to append it to a div. In php I created a json array containing the following html code:

<li id="1234">
   <span class="some">$1</span>
   <span class="some2">$1</span>
   <div class="somediv"></div>
</li>

So the whole json array looks like this:

[{"id":"12435","text":"<li id=\"1234\"><span class=\"some\">$1</span>"},{"id":"13542","text":"<span class=\"some2\">$1</span><div class=\"somediv\"></div></li>"}];

Now I used getJSON to get the json object and then I append the result to a div like this: $(".container").append(val);

Now the problem is that somehow when trying to append the JSON results, this is what is beeing appended:

<li id="1234">
   <span class="some">$1</span>
</li>
<li id="1234">
   <span class="some2">$1</span>
   <div class="somediv"></div>
</li>

When I try to output my val with alert(val) it clearly shows that the json result is correct (without the closing <li> tag), but when appending it, the <li> tag is added.

Does anyone have any idea what could be the reason for this?

This is how I get the values from my php file:

$.getJSON("../ajax.php?action=getresults", function(data)
        {
            var obj = $.parseJSON(data);

            $.each(obj, function(key,val)
            {
                $.each(obj[key], function(key, dval)
                {
                    if(key == "text")
                    {
                        alert(dval);
                        $(".container").append(dval);
                    }
                })          

            });         

        });
  • 写回答

4条回答 默认 最新

  • dpswo40440 2012-12-17 19:08
    关注

    Currently you have your html tags closing in the second array. So you are going to have to store all the html gathered into a var before appending it.

    var html = '';
    
    $.each(obj[key], function(key, dval)
    {
        if(key == "text")
        {
            alert(dval);
            html += dval;
        }
    });
    
    $('.container').append(html);  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化