我需要帮助在html中生成换行符.
var x = "jun"; var y = "2015"; var calculate= x + "<br>" + y;
Html返回如下
<div>jan <br> 2015</div>
预期结果:我需要在html中换行,但不应该渲染< br>标签.
更新:我想要的是“jan”在第一行和下一行“2015”
我在c3图表x值中使用这些值.
提前致谢.
解决方法
你的问题陈述有点不高兴:你正在使用C3.js,它将生成svg元素.
因此返回的标记实际上是< tspan dx =“0”dy =“.71em”x =“0”> 0& lt; br& gt; 2014< / tspan>.
C3将使用tspan的textContent属性来追加函数返回的文本内容.
正如在other questions中已经说过的那样,你不能在< tspan>中添加换行符.元素.
因此,该解决方案有效地在另一个之下创建新的tspan,在相同的< text>中.元件.
不幸的是,没有办法获得这些精确的元素,除非通过循环所有其他tspans,所以这听起来像一个真正的黑客,但这里是一个脚本,将做你想要的…
// get our svg doc var svg = document.querySelector('svg'); // get our tspans element var tspans = svg.querySelectorAll('tspan'); // transform it to an array so the clones don't add to the list var ts = Array.prototype.slice.call(tspans); for(var i = 0; i<ts.length; i++){ // get the content var cont = ts[i].textContent.split('\n'); // that wasn't the good one... if(cont.length<2) continue; // create a clone var clone = ts[i].cloneNode(1); // set the text to the new line clone.textContent = cont[1]; // space it a litlle bit more clone.setAttribute('dy','0.9em') // set the good text to the upperline ts[i].textContent = cont[0]; // append our clone ts[i].parentNode.insertBefore(clone,ts[i].nextSibling) };
var chart = c3.generate({ data: { json: [{ date: '2014-01-01',upload: 200,download: 200,total: 400 },{ date: '2014-01-02',upload: 100,download: 300,{ date: '2014-02-01',upload: 300,total: 500 },{ date: '2014-02-02',upload: 400,download: 100,total: 500 }],keys: { x: 'date',value: ['upload','download'] } },axis: { x: { type: 'timeseries',tick: { format: function (x) { if (x.getDate() === 1) { return x.getMonth() + '\n' + x.getFullYear(); } } } } } }); // get our svg doc var svg = document.querySelector('svg'); // get our tspans element var tspans = svg.querySelectorAll('tspan'); // transform it to an array so the clones don't add to the list var ts = Array.prototype.slice.call(tspans); for(var i = 0; i<ts.length; i++){ // get the content var cont = ts[i].textContent.split('\n'); // that wasn't the good one... if(cont.length<2) continue; // create a clone var clone = ts[i].cloneNode(1); // set the text to the new line clone.textContent = cont[1]; // space it a litlle bit more clone.setAttribute('dy',ts[i].nextSibling) };
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script> <link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"> <div id="chart"></div>