gpt4 book ai didi

jquery - 如何在 html/jquery 中为字符串/单词着色

转载 作者:太空宇宙 更新时间:2023-11-04 13:28:57 25 4
gpt4 key购买 nike

我正在尝试为 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

关于jquery - 如何在 html/jquery 中为字符串/单词着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23501627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com