最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to append a variable to an HTML element stored as string using Jquery? - Stack Overflow

programmeradmin0浏览0评论

I have an empty controlgroup, which I want to populate with buttons. Can't get it to work.

This is the controlgroup:

var $wrap = '<div class="wrap"><div data-role="controlgroup"></div></div>';

This is the button:

var $btn = '<a href="#some" data-role="button">Click</a>'

I want to do something like this:

$wrap.append( $btn );

But it's not working.

Can someone tell me what I'm doing wrong? I think $wrap is just a string, so I cannot call append on it. If so, how do I do it correctly?

Thanks for help!

I have an empty controlgroup, which I want to populate with buttons. Can't get it to work.

This is the controlgroup:

var $wrap = '<div class="wrap"><div data-role="controlgroup"></div></div>';

This is the button:

var $btn = '<a href="#some" data-role="button">Click</a>'

I want to do something like this:

$wrap.append( $btn );

But it's not working.

Can someone tell me what I'm doing wrong? I think $wrap is just a string, so I cannot call append on it. If so, how do I do it correctly?

Thanks for help!

Share Improve this question asked Apr 13, 2012 at 17:06 frequentfrequent 28.5k61 gold badges187 silver badges336 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2
var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');
var $btn = $('<a href="#some" data-role="button">Click</a>');
$wrap.append( $btn );

There's probably fifty ways to this, like:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>'),
    $btn = '<a href="#some" data-role="button">Click</a>';

$wrap.children().append( $btn );

or:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>'),
    $btn = '<a href="#some" data-role="button">Click</a>';

$('[data-role="controlgroup"]', $wrap).append( $btn );

You simply have strings, you need a jquery object to call append:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');

Well, first off, those are strings. You'll want to turn them into jQuery objects using $.

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');
var $btn = $('<a href="#some" data-role="button">Click</a>');

Now to append $btn into $wrap, you can go find the inner div (which is where you want to append the element) and use .append:

$wrap.find("div").append($btn);

Live example

I think $wrap is just a string, so I cannot call append on it.

Yes.

You could try:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');
var $btn = '<a href="#some" data-role="button">Click</a>';
$wrap.append( $btn );
发布评论

评论列表(0)

  1. 暂无评论