简体   繁体   中英

Refresh X div elements at once using an html button. How to make my code shorter?

I have three divs and one button . In to my jQuery script, everytime I click on button, those three divs elements refreshed at once.

HTML Code

<input id="refresh" type="button" value="Refresh"/>
<div id="R1">Value 1</div>
<div id="R2">Value 2</div>
<div id="R3">Value 3</div>

JQUERY CODE

var $JQ_ = jQuery.noConflict();

$JQ_(document).ready(function () {

    $JQ_("#refresh").click(function () {
        $JQ_("#R1").load("index.php#R1").fadeOut(1000).fadeIn(1000);
    });
    $JQ_("#refresh").click(function () {
        $JQ_("#R2").load("index.php #R2").fadeOut(1000).fadeIn(1000);
    });
    $JQ_("#refresh").click(function () {
        $JQ_("#R3").load("index.php #R3").fadeOut(1000).fadeIn(1000);
    });
});

JSFIDDLE Example here .

What I want to do is to make my code shorter and not to have to write the same thing for all my divs. In to an other script I am using something like this

 $JQ_("[id^='opener_']").click(function () {
     $JQ_("#dialog_" + this.id.split('_')[1]).dialog("open");
 });

but this is an other case. Any idea how can I make my code work like this?

<input id="refresh" type="button" value="Refresh"/>
<div id="R1" data-url="index.php #R1" class="thing">Value 1</div>
<div id="R2" data-url="index.php #R2" class="thing">Value 2</div>
<div id="R3" data-url="index.php #R3" class="thing">Value 3</div>

Add a class to each "thing". In the click event, loop through each "thing", get the url to load the data from the data-url attribute, and do the stuff:

$JQ_("#refresh").click(function() {
    $JQ_('div.thing').each(function() {
        var url = $JQ_(this).data('url');

        $JQ_(this).load(url).fadeOut(1000).fadeIn(1000);
    });
});

Put the divs you want to refresh into one class and use the class identifier for your jQuery code. This will allow you to run jQuery code on multiple divs without having to copy-paste the same code for each div.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM