因此,我有一个网站,该网站有一个随机加载的幻灯片,其中包含为每张幻灯片调用文本的 div 容器。我希望能够为特定单词添加链接和/或颜色更改。这是我目前拥有的 JSFIDDLE 链接:http://jsfiddle.net/shadna/Agq7W/
为方便起见,这里是编码:
JS::
jQuery(function($){
$('#homebanner').css({backgroundColor: "#000"});
var totalCount = 4;
var num = Math.ceil( Math.random() * totalCount );
var hText = ["WE SPEAK ARCHITECTURE", "WE HAVE HIGH SPIRIT(S)", "STRATEGY: BUILT ON HUMAN-CENTERED", "FOREVER IN BLUE JEANS"];
var hsubText = ["CLIENT: EDA ARCHITECTS", "CLIENT: HIGH WEST DISTILLERY", "CLIENT: ARCHITECTURAL NEXUS", "CLIENT: VAULT DENIM"];
function setBGImage() {
var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/'+num+'.jpg';
$('#homebanner').css({
backgroundImage:"url("+bgimage+")",
});
$('#htxt').html(hText[num - 1]);
$('#hsubtxt').html(hsubText[num - 1]);
}
setBGImage();
});
HTML::
<div id="homebanner">
<div id="hwrap">
<div id="htxt"></div>
<div id="hsubtxt"></div>
</div>
</div>
任何信息都会对这个谦虚的 JS 学习者有所帮助。
最佳答案
首先,一些简化和修改代码:
jQuery(function ($) {
$('#homebanner').css({
backgroundColor: "#000"
});
// put all the information in the same place, in this case an
// array of objects:
var details = [{
head: 'WE SPEAK ARCHITECTURE',
sub: 'EDA ARCHITECTS',
link: 'http://example.com/edaarchitects.html'
}, {
head: 'WE HAVE HIGH SPIRIT(S)',
sub: 'HIGH WEST DISTILLARY',
link: 'http://example.com/highwestdistillary.html'
}, {
head: 'STRATEGY: BUILT ON HUMAN-CENTERED',
sub: 'ARCHITECTURAL NEXUS',
link: 'http://example.com/architecturalnexus.html'
}, {
head: 'FOREVER IN BLUE JEANS',
sub: 'VAULT DENIM',
link: 'http://example.com/vault-denim.html'
}],
// use the length of the details array to work out the upper bounds
// of the random number in order to allow for easier updating:
num = Math.floor(Math.random() * details.length),
// cache the relevant object for later use:
item = details[num];
function setBGImage() {
// using '(num + 1)' because your images aren't zero-indexed (for some reason):
var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/' + (num + 1) + '.jpg';
$('#homebanner').css({
backgroundImage: "url(" + bgimage + ")",
});
$('#htxt').html(item.head);
// I've taken 'CLIENT: ' out of the 'sub' since it was in all of them.
// creating an 'a' element using the 'link' information from the object:
$('#hsubtxt').html('CLIENT: ' + '<a href="' + item.link + '">' + item.sub + '</a>');
}
setBGImage();
});
关于javascript - 如何在 JS 中向 var 字符串添加链接或颜色更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733285/