Condensing jQuery function -


so, have following jquery (ajax).

jquery("button1").click(function(){     jquery("#div1").load("demo_test.txt"); }); jquery("button2").click(function(){     jquery("#div2").load("demo_test.txt"); }); jquery("button3").click(function(){     jquery("#div3").load("demo_test.txt"); }); jquery("button4").click(function(){     jquery("#div4").load("demo_test.txt"); }); jquery("button5").click(function(){     jquery("#div5").load("demo_test.txt"); }); 

as can see, have 5 buttons , 5 divs.

is there way minify jquery functions?

thanks

supposing divs have different purposes , need different.

there many ways achieve this. 1 using for, not practice these cases.

you otherway make buttons belong same class, , select div according related (for example parent) element of $(this). not posting html code, assume div contains button.

js

jquery(".mybtnclass").click(function(){     var mydiv = $(this).parent('div');     jquery(mydiv).load("demo_test.txt"); }); 

html

<div>    <button class="mybtnclass" value="click me1" /> </div>  <div>    <button class="mybtnclass" value="click me2" /> </div> 

this target container div , overwrite it's contents, removing clicked button.


another (sintactically more complex) approach target div element's id, using data html attributes, , div can me anywhere in document, not containing button.

js

jquery(".mybtnclass").click(function(){     var mydiv = $(this).data('banner');     jquery('#'+mydiv).load("demo_test.txt"); }); 

html

<button class="mybtnclass" value="click me1" data-banner="banner1" /> <div id="banner1"></div>  <button class="mybtnclass" value="click me2" data-banner="justanothername" /> <div id="justanothername"></div> 

Comments