我尝试更改顶部div,因此当选择任一按钮时,它会根据点击的按钮更改它。
HTML
<div class="bulb" id="bulb1"></div>
<div class="bulb" id="bulb2"></div>
<button id="blue">blue</button>
<button id="yellow">yellow</button>
JQUERY
$( document ).ready(function() {
// initial load up coverts to this colour
$('.bulb1').css("background-color","black");
//call the colour change functions when clicked
$('#blue').click("background-color", "setBlue");
$('#yellow').click("background-color", "setYellow");
});
function setYellow(){
$('#bulb1').css("background-color","#yellow");
}
function setBlue(){
$('#bulb1').css("background-color","#blue");
}
答案 0 :(得分:3)
尝试这样的事情:
$('#blue').click(function() {
$('#bulb1').css({
'background-color' : 'blue'
});
});
或者
$('#blue').click(function() {
setBlue();
});
function setBlue() {
$('#bulb1').css({
'background-color': 'blue'
});
}
您可以重构代码,如:
$(document).ready(function() {
// initial load up coverts to this colour
setColor('black');
//call the colour change functions when clicked
$('#blue').click(function() {
setColor('blue');
});
$('#yellow').click(function() {
setColor('yellow');
});
});
function setColor(color) {
$('#bulb1').css({
'background-color': color
});
}
答案 1 :(得分:1)
您最初选择了错误的元素:
$('.bulb1').css("background-color","black");
应该是
$('#bulb1').css("background-color","black");
或
$('.bulb').css("background-color","black");
取决于您尝试选择的元素。
答案 2 :(得分:1)
根据您的代码进行更正和解决方案 -
$( document ).ready(function() {
// initial load up coverts to this colour
$('#bulb1').css("background-color","black");
//call the colour change functions when clicked
$('#blue').click(function(){
setBlue();
});
$('#yellow').click(function(){
setYellow();
});
});
function setYellow(){
$('#bulb1').css("background-color","yellow");
}
function setBlue(){
$('#bulb1').css("background-color","blue");
}
答案 3 :(得分:0)
$( document ).ready(function() {
// initial load up coverts to this colour
$('.bulb').css("background-color","black");
//call the colour change functions when clicked
$('#blue').click(function()
{
$('#bulb1').css("background-color","blue");
});
$('#yellow').click(function()
{
$('#bulb1').css("background-color","yellow");
});
});
答案 4 :(得分:0)
试试这个:
$('#yellow').click(setYellow);
$('#blue').click(setBlue);
或委派click命令来监听文档中元素的“click”事件:
$(document).delegate('#yellow', 'click', setYellow);
$(document).delegate('#blue', 'click', setBlue);