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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度