这些是当前的代码片段。
我尝试了几种不同的方法,但似乎没有任何效果。
请帮忙!!!
HTML片段
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
jQuery片段
var backgroundImg = ['../images/heroBG.jpg', '../images/heroBG2.jpg'
];
var backgroundCount = 0;
$(function () {
$('hero').css('background', 'url(' + backgroundImg[backgroundCount] + ')');
});
$('myonoffswitch').on('click', function () {
backgroundCount++;
if (backgroundCount > backgroundImg.length - 1) backgroundCount = 0;
$('hero').css('background', 'url(' + backgroundImg[backgroundCount] + ')');
});
最佳答案
在jQuery中按ID引用元素时,您需要使用#$('myonoffswitch')
将检查任何html
元素名称myonoffswitch
。要获取ID为myonoffswitch
的元素,您需要使用$('#myonoffswitch')
$('#myonoffswitch').on('click', function () {
backgroundCount++;
if (backgroundCount > backgroundImg.length - 1) backgroundCount = 0;
//Assuming hero is ID of some element
$('#hero').css('background', 'url(' + backgroundImg[backgroundCount] + ')');
});