<html> <head></head> <style> #content,#ad,#study{ width:200px; height: 100px; border: 1px solid black; } </style> <body> <h1>observe</h1> <select name="" id=""> <option value="male">male</option> <option value="female">female</option> </select> <input type="button" onclick="t1()" value="观察ad"> <input type="button" onclick="t2()" value="不观察ad"> <div id="content">content</div> <div id="ad">ad</div> </body> <script> //select为被观察 下面内容为观察 var sel=document.getElementsByTagName(‘select‘)[0]; sel.observers={} //把观察的记录号 sel.attach=function(key,obj){ sel.observers[key]=obj; } sel.detach=function(key){ delete this.observers[key]; } sel.onchange=sel.notify= function () { for(var key in this.observers){ this.observers[key].update(this); } } var content=document.getElementById(‘content‘); var ad=document.getElementById(‘ad‘); content.update=function (observee) { if(observee.value==‘male‘){ this.innerHTML=‘car‘; }else if(observee.value=‘female‘){ this.innerHTML=‘jianfei‘; } } ad.update=function (observee) { if(observee.value==‘male‘){ this.innerHTML=‘male_ad‘; }else if(observee.value=‘female‘){ this.innerHTML=‘female_ad‘; } } //让content观察select的变化 sel.attach(‘content‘,content); function t1(){ sel.attach(‘ad‘,ad); } function t2(){ sel.detach(‘ad‘); } </script> </html>
时间: 2024-10-06 05:17:56