Correction status:Uncorrected
Teacher's comments:
此案例展示了jQuery利用多种选择器对页面元素的控制,通过点击按钮实现图片的转换
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery选择器实现对图片的控制</title> <style type="text/css"> table { border-collapse: collapse; border:1px solid skyblue; margin:50px auto; text-align: center; } table caption { margin-bottom:30px; } td { padding:10px; border:1px solid skyblue; } button { border:none; width:140px; height:50px; background-color: orange; color:#fff; font-size:1.2em; } button:hover { font-size:1.3em; background-color: coral; } </style> </head> <body> <div class="box"> <table> <caption><h2>jQuery选择器实现对图片的控制</h2></caption> <tr> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="1"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="2"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="3"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="4"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="5"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="6"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="7"></td> <td><img src="http://www.w3school.com.cn/i/eg_bulboff.gif" alt="8"></td> </tr> <tr> <td><button>1</button></td> <td><button>2</button></td> <td><button>3</button></td> <td><button>4</button></td> <td><button>5</button></td> <td><button>6</button></td> <td><button>7</button></td> <td><button>8</button></td> </tr> <tr> <td colspan="3"><button>点亮前三盏</button></td> <td colspan="2"><button>点亮中间两盏</button></td> <td colspan="3"><button>点亮后三盏</button></td> </tr> <tr> <td colspan="8"> <button>全部点亮</button> <button>点亮单数</button> <button>点亮偶数</button> </td> </tr> </table> </div> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <script type="text/javascript"> for (var i = 0; i <= 7; i++) { $('button')[i].onclick = function(){ if ($('img')[this.innerHTML-1].src.match("bulbon")) { $('img')[this.innerHTML-1].src="http://www.w3school.com.cn/i/eg_bulboff.gif"; } else { $('img')[this.innerHTML-1].src="http://www.w3school.com.cn/i/eg_bulbon.gif"; } } } var changesrc var changeinnerHTML for (var i = 8; i <= 13; i++){ $('button')[i].onclick = function(){ if (this.innerHTML == "点亮前三盏") { changesrc = "img:lt(3)" } else if (this.innerHTML == "点亮中间两盏") { changesrc = "img:gt(2):lt(2)" } else if (this.innerHTML == "点亮后三盏") { changesrc = "img:gt(4)" } else if (this.innerHTML == "全部点亮") { changesrc = "img" } else if (this.innerHTML == "点亮单数") { changesrc = "img:even" } else if (this.innerHTML == "点亮偶数") { changesrc = "img:odd" } $(changesrc).attr('src','http://www.w3school.com.cn/i/eg_bulbon.gif') } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例