1

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?

4

2 回答 2

4
<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>

为每个“事物”添加一个类。在 click 事件中,循环遍历每个“事物”,从 data-url 属性中获取加载数据的 url,然后执行以下操作:

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

        $JQ_(this).load(url).fadeOut(1000).fadeIn(1000);
    });
});
于 2013-10-24T18:11:26.790 回答
2

将要刷新的 div 放入一个类中,并为您的 jQuery 代码使用类标识符。这将允许您在多个 div 上运行 jQuery 代码,而不必为每个 div 复制粘贴相同的代码。

于 2013-10-24T18:07:21.757 回答