我正在尝试为 HTML 中的字符串/单词着色。我在这里找到了回复 - 但我无法理解如何转换为多次使用该函数..
http://jsfiddle.net/8VDm4/
<div id="arch" style="font-size: 40px">First Word work fine</div>
<div id="arch" style="font-size: 40px">Second time - does not work</div>
var colours = ["#635636", "#FF00C0", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
idx;
$(function() {
var div = $('#arch');
var chars = div.text().split('');
div.html('');
for(var i=0; i<chars.length; i++) {
idx = Math.floor(Math.random() * colours.length);
var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx]);
div.append(span);
}
});
如何创建一个可以在 HTML 中多次调用的函数?
您只能拥有一个具有特定 id
的元素。将您的 id
替换为 class
(或向元素添加特定的类),如下所示
<div class="arch" style="font-size: 40px">First Word work fine</div>
<div class="arch" style="font-size: 40px">Second time - does not work</div>
javascript
//code has been update in response of observation made by adeneo, thanks adeneo
var colours = ["#635636", "#FF00C0", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
idx;
$(function () {
$('.arch').each(function () {
var div = $(this),
chars = div.text().split(''),
span = '';
div.html('');
for (var i = 0; i < chars.length; i++) {
idx = Math.floor(Math.random() * colours.length);
span = span + $('<div>').append($('<span>' + chars[i] + '</span>').css('color', colours[idx])).html();
}
div.append(span);
});
});
我添加了一些代码以避免频繁更新 DOM
我是一名优秀的程序员,十分优秀!