简体   繁体   English

在添加div时添加空格

[英]add white space when create a div when prepend

I use this 我用这个

$("#containerSeparateChart").prepend("<div class="+ key +"></div>")

to create dynamic div when I click a button depend on the key I create the name of the class, but now I want to add one more class for example col-xs-6 在单击按钮时创建动态div取决于键,我创建了类的名称,但是现在我想再添加一个类,例如col-xs-6

I try this 我尝试这个

$("#containerSeparateChart").prepend("<div class="+ key +"col-xs-6"+"></div>")

this add the class but, together like this class="keynamecol-xs-6" and I want a space between the name like this class="keyname col-xs-6" 这种添加的类别,但是,这样在一起class="keynamecol-xs-6" ,我想这样的名字之间的空间class="keyname col-xs-6"

I try to use all this option 我尝试使用所有这些选项

  • $("#containerSeparateChart").prepend("<div class="+ key +" col-xs-6"+"></div>")

  • $("#containerSeparateChart").prepend("<div class="+ key +"&nbsp;col-xs-6"+"></div>")

  • $("#containerSeparateChart").prepend("<div class="+ key + " "+"col-xs-6"+"></div>")

But all this case create something like this 但是所有这些情况都创建了这样的东西

class="keyname" "col-xs-6"

Any idea what I doing wrong! 知道我做错了!

thanks in advance! 提前致谢!

jQuery: jQuery的:

var child = $('<div>').addClass(key + ' col-xs-6')
$("#containerSeparateChart").prepend(child)

Without jQuery: 没有jQuery:

var child = document.createElement('div');
child.classList.add(key)
child.classList.add('col-xs-6');

document.querySelector("#containerSeparateChart").appendChild(child)

es6 jQuery: es6 jQuery:

$("#containerSeparateChart").prepend(`<div class="${key} col-xs-6"></div>`)

Just a small issue with your quotes: 您的报价只是一个小问题:

$("#containerSeparateChart").prepend('<div class="' + key + ' col-xs-6"></div>');

Example: https://jsfiddle.net/qv49p1az/1/ 示例: https //jsfiddle.net/qv49p1az/1/


Side note: If you are not already, I would recommend using a code editor (IDE) such as Atom ( http://atom.io ). 旁注:如果您还没有,我建议使用代码编辑器(IDE),例如Atom( http://atom.io )。 Most modern editors would typically pick up on syntax errors like this. 大多数现代编辑器通常会遇到这样的语法错误。

Use this: 用这个:

$("#containerSeparateChart").prepend('<div class="' + key + ' col-xs-6"></div>');

You need to alternate your quotes to properly concatenate the variable key . 您需要替换引号以正确地连接变量key No need to use a non-breaking space for separation of classes - a simple white space will do. 无需使用不间断的空格来分隔类,只需一个简单的空白即可。

$("#containerSeparateChart").prepend('<div class="' + key + ' col-xs-6"></div>')

ES2015:

$("#containerSeparateChart").prepend(`<div class="${key} col-xs-6"></div>`)

Did you try this? 你有尝试过吗?

$("#containerSeparateChart").prepend("<div class="+ key +"></div>");
$('.' + key).addClass('col-xs-6');

您的第一种方法是正确的,但是您的报价有误

$("#containerSeparateChart").prepend("<div class='"+ key +" col-xs-6"+"'></div>")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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