从数组中附加宽度值的td

时间:2017-10-12 00:01:57

标签: javascript jquery html css

我有一个数组如下,我喜欢它们是我想要追加的<td>的宽度。

<table>
  <tr class="table_row">
  </tr>
</table>

<script>
var arr = [40, 60, 80, 100]
var table_row = $('.table_row');
for(var i=0; i<arr.length  i++){
  table_row.append('<td style="width:arr[i]></td>')
}
</script>

我想我需要连接arr[i]

2 个答案:

答案 0 :(得分:1)

您忘记了for中的分号:

for(var i=0; i<arr.length  i++){
//-----------------------^ here

当您定义要附加的td时:

table_row.append('<td style="width:arr[i]"></td>');

您正在放置文本arr[i]而不是数组值。还缺少width单位,您可以将其设置为px

要修复数组值问题,您可以连接:

table_row.append('<td style="width:' + arr[i] + '"></td>');

或使用String interpolation

table_row.append(`<td style="width:${arr[i]}"></td>`);

请注意,通过插值,outter ticks从'变为`。

修复一切:

var arr = [40, 60, 80, 100];
var table_row = $('.table_row');
for(var i=0; i<arr.length; i++){
  table_row.append(`<td style="width:${arr[i]}px;">&nbsp;</td>`);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr class="table_row">
  </tr>
</table>

请注意,我在&nbsp;中添加了td,在border中添加了table,以便您可以更好地在实时代码段中看到结果

答案 1 :(得分:0)

const questionBlock = document.querySelector('.card-container');
const questionCard = document.querySelector('.card');

function build() {
    let output = [];

    ...some unimportant code here...

      output.push(
        `
          <div class='card'>
            <div class='question'>${current.question}</div>
            <div class='answers'>${answers.join('')}</div>
          </div>
        `
      );
    })

    questionBlock.innerHTML = output;
}

build();

尝试使用它。