我正在尝试将类和 ID 分配给我在 js 中创建并输入到我的 html 中的数组中的元素。我这样做是为了在我的样式表中设置它们的样式。每个元素的样式都不会相同。
我是一个初学者,所以尽量保持我能理解的代码并使其尽可能干净,即不要让这些元素中的每一个成为 html 中的元素。
这部分工作正常:
var pool =['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U']
var letters = pool.join('');
document.getElementById('key').innerHTML = letters;
这部分没那么多:
var char1 = letters[1];
char1.classList.add('hoverRed');
有个类似的问题here这对我不起作用,它只是在我运行时显示 [object][object][object]
。
最佳答案
您的代码试图将样式应用于数组元素,但 CSS 仅适用于 HTML。如果您希望为字符串中的一个字符设置样式,则该字符必须包装在 HTML 元素中(<span>
是包装内联值的最佳选择)。
此代码显示了如何完成此操作:
var pool =['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U']
var letters = pool.join('');
// Replace a specific character with the same character, but wrapped in a <span>
// so it can be styled
letters = letters.replace(letters[1], "<span>" + letters[1] + "</span>");
// Insert the letters string into the div
var theDiv = document.getElementById('key');
// Inject the string into the div
theDiv.innerHTML = letters;
// Get a reference to the span:
var theSpan = theDiv.querySelector("span");
// Add the style to the <span> that wraps the character, not the character itself
theSpan.classList.add('hoverRed');
.hoverRed {
color:red;
}
<div id="key"></div>
并且,此代码段展示了如何将 CSS 应用于任何字母:
var pool =['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U'];
// Leave the original array alone so that it can be manipulated any way needed
// in the future, but create a new array that wraps each array element within
// a <span>. This can be accomplished in several ways, but the map() array method
// is the most straight-forward.
var charSpanArray = pool.map(function(char){
return "<span>" + char + "</span>";
});
// Decide which character(s) need CSS applied to them. This data can come from anywhere
// Here, we'll just say that the 2nd and 5th ones should.
// Loop through the new array and on the 2nd and 5th elements, apply the CSS class
charSpanArray.forEach(function(element, index, array){
// Check for the particular array elements in question
if(index === 1 || index === 4){
// Update those strings to include the CSS
array[index] = element.replace("<span>","<span class='hoverRed'>");
}
});
// Now, turn the new array into a string
var letters = charSpanArray.join('');
// For diagnostics, print the string to the console just to see what we've got
console.log(letters);
// Get a reference to the div container
var theDiv = document.getElementById('key');
// Inject the string into the div
theDiv.innerHTML = letters;
.hoverRed {
color:red;
}
<div id="key"></div>
关于javascript - 为 css 样式分配 javascript 数组元素类或 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968593/