简体   繁体   中英

Why does my JQuery script add html tags when appending it?

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);
                    }
                })          

            });         

        });

jQuery is appending HTML, but you are passing it partial HTML blocks. Try concatenating all of the HTML into a single value and then appending it.

jQuery methods expect complete dom nodes. jQuery methods are designed to automatically create elements from only half-written tags, so this may not be as easy as you had hoped.

One alternative would be to build the string in JavaScript and append when complete. Alternatively, you could likely do this with vanilla JavaScript. I'd warn against it though, as any error could leave the page in a nasty state.

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

你有尝试过吗?

$(".container").html(val);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM