开发者

jquery variable as div ID or class

开发者 https://www.devze.com 2023-01-20 06:29 出处:网络
var $name = (\'div#a开发者_开发知识库muchlongername\'); $(\'#wrapper\').prepend(\'<div id=\"$name\"></div>\');
var $name = ('div#a开发者_开发知识库muchlongername');

    $('#wrapper').prepend('<div id="$name"></div>');

Obviously I know this code is wrong lol, but I'm fairly knew to jQuery and I can't seem to find anything about this.

How would one go about achieving a variable name inside a div id?


You would go about it in the same way as normal JavaScript (since it's just a string passed to jQuery).

var name = 'amuchlongername'
$('#wrapper').prepend('<div id="' + name + '"></div>');

name is just a normal JavaScript variable and can be anything. The $ is an alias for jQuery. When you do $('#wrapper') you are calling jQuery to access the element with the Id of wrapper.

I've made a jsFiddle to show it working: http://jsfiddle.net/Xs45x/1/ I've just updated it to put the variable inside the div too, so you can see what it's doing.


i'm no js expert but try

var $name = ('div#amuchlongername');

('#wrapper').prepend('<div id="' + $name + '"></div>');

also i don't think you need the $ sign for variables. Might be wrong

0

精彩评论

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

关注公众号