分配期间的JavaScript字符串连接

JavaScript String Concatenation during Assignment

本文关键字:字符串 连接 JavaScript 分配      更新时间:2023-09-26

我正在构建一个按钮集合,每个按钮都将被分配给一个变量。在我的循环中,我有一些id,我想将其附加到每个按钮的id属性:

var test = '<button id="myButton_" class="myButtonsClass" type="button">testButton</button>';

我希望它看起来像button id="myButton_123"

避免长字符串,并使用DOM本身提供给您的方法。创建元素,并操纵它们的内容/属性并不困难:

// This will hold our buttons, so we aren't thrashing the DOM
var fragment = document.createDocumentFragment();
// Lets cycle over a collection of ids
[ 23, 57, 92 ].forEach(function ( id ) {
    // Create a button, and get ready to manipulate it
    var button = document.createElement( "button" );
    // Set a few properties, and the content
    button.id = "myButton_" + id;
    button.textContent = "Test Button";
    button.className = "myButtonsClass";
    // Push this button into the fragment
    fragment.appendChild( button );    
});
// Now we touch the DOM once by adding the fragment
document.body.appendChild( fragment );

在现代ES6+环境中,您可以在situe插值中使用的模板文本字符串:

var id = "73868CB1848A216984DCA1B6B0EE37BC";
var button = `<button id='myButton${ id }'>Click Me</button>`;

话虽如此,我仍然鼓励您将任务分解为更小、更易消耗的部分,并使用DOMapi来构建元素。

您可以使用替换函数:

var template = '<button id="myButton_#" class="myButtonsClass" type="button">testButton</button>';
for (var i=0; i<10, i++) {
   console.log(template.replace('#',i));
}