简体   繁体   中英

how to append a variable to an HTML element stored as string using Jquery?

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!

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

您仅具有字符串,就需要一个jquery对象来调用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 );

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