开发者

Jquery problem: adding something to a jquery object

I want to add a string at the end of a jquery object. Something like this:

var mytable = $("<table><tbody><tr><td>");
mytable.after("Test</td></tr></t开发者_运维技巧body></table>");

I tried with that too

mytable += "Test</td></tr></tbody></table>";

Doesn't work either.


jQuery doesn't work that way. When you're dealing with elements in jQuery they are always valid. If it can't validate it, it won't add it. I tried your example and jQuery completed the invalid HTML:

var mytable = $("<table><tbody><tr><td>");    
// mytable is equal to $("<table><tbody><tr><td></td></tr></tbody></table>");

If you're looking to add a new cell to your table, you could select the required element (i.e. the tr) and then use the append method

mytable.find("tr").append("<td>New cell</td>");

Of course, you can add two strings together and put them in a jQuery object as long as they join to make valid HTML

var string1 = "<table><tbody><tr><td>First half and";
    string1 = " second half</td></tr></tbody></table>";

mytable = $(string1 + string2);


Problem here is that

"<table><tbody><tr><td>" //jQuery will try to create full html elements from what you enter

is not valid html nor is

"Test</td></tr></tbody></table>" // this will never work, cause this tags are closing only and the table might have been already build when the line before gets executed

jQuery might be able to create valid elements from not fully valid html, but this does not work in every case. I suggest you try to work with valid html!!!


jQuery cannot create page elements unless you provide full valid HTML. I'm not sure of your exact needs but you should do something on this line:

var mytable = $("<table><tbody><tr><td></td></tr></tbody></table>").find("td").text("Test");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜