分配期间的JavaScript字符串连接
JavaScript String Concatenation during Assignment
我正在构建一个按钮集合,每个按钮都将被分配给一个变量。在我的循环中,我有一些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));
}
相关文章:
- 当附加到DOM时,可以将变量与字符串连接起来吗?它能处理逃跑吗
- 将变量与字符串连接以定义另一个变量
- AJAX 后请求和字符串连接
- 哪种方式在Javascript,字符串连接或数组中更好
- Javascript 字符串连接错误
- Javascript - 使用字符串连接设置变量
- 换行符及其在 Javascript 中的字符串连接中的作用
- 下划线.js if 语句上的字符串连接
- 以下jQuery字符串连接代码有什么问题
- XMLHttpRequest 中表单数据上的 Javascript 二进制字符串连接
- JavaScript 字符串连接不起作用
- 是否可以在 JavaScript 中将 OBJ 与字符串连接起来
- Jquery 字符串连接
- 谁能解释这种关于字符串连接的奇怪 JS 行为
- 将我的对象与字符串连接
- JavaScript 中的字符串连接
- 分配期间的JavaScript字符串连接
- 在AngularJS中使用HTML img src中的字符串连接
- JavaScript-将多个字符串连接在一起
- 字符串连接与 ( document.getElementById().value).