2011-10-16 30 views
0

我正在使用腳本,需要製作多個事件才能使彈出窗口顯示。javascript - 用於循環制作事件

我嘗試這樣做,但它不工作:

for (i=0;i<=storingen;i++) 
    { 
     $("#storing" + i).click(function(){ centerPopup(); loadPopup(); }); 
    } 

輸出應該是:

$("#storing0").click(function(){ centerPopup(); loadPopup(); }); 
$("#storing1").click(function(){ centerPopup(); loadPopup(); }); 
$("#storing2").click(function(){ centerPopup(); loadPopup(); }); 
$("#storing3").click(function(){ centerPopup(); loadPopup(); }); 

不過的div id爲#storing量(號碼在這裏)是可變的,所以我想這樣做,但它不工作...

我從PHP得到storingen變量:

<script type="text/javascript">aantalstoringen('.$aantalstoringen.')</script> 

我在js文件這樣的回暖:

function aantalstoringen(storingen){ 
    storingen=storingen; 
} 

我做了一個警報(storingen),其追溯權數,這樣就可以了。

難道是for循環行不通的,因爲心不是在aantalstoringen功能,但在另一個功能:

$(document).ready(function() { 

我用這個教程做的JavaScript: http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-using-jquery/#popup1 和腳本你得到的是這樣的: http://yensdesign.com/tutorials/popupjquery/popup.js

+0

我建議你給所有這些元素的同一類,只是做'$(「類名」)。點擊(函數( ){...});'。 –

+0

此外,我想指出,這個功能是[如你可以在鏈接的popup.js文件中看到的]顯示特定的div。 每個div有不同的ID,因爲內容不同,所以我不能使用該功能來搜索ID存儲的每個元素* 如果我不是很清楚,我很抱歉。 – laarsk

回答

0

不創建幾十個調用相同的處理事件偵聽器。您可以在DOM中的較高級別上創建一個偵聽器,並僅在目標ID與該模式匹配時才作出反應。

這就是爲什麼像jQuery庫是教孩子壞習慣...... -.-

+0

是的,你知道,我意識到我使用的腳本在這裏完全不方便使用,因爲它們都稱爲相同的處理程序... 我必須讓不同的eventlistener調用不同的處理程序來完成這項工作... 我有多愚蠢 – laarsk

1

使用[name^="value"]選擇,而不是:

$('[id^="storing"]').click(function(){ ... }); 

基本上,它說「找到所有元素的ID以'存儲'開始。」

如果您更明確地需要它,可以測試each()中的id以應用更好的過濾。例如

$('[id^="storing"]') 
    // make sure all IDs end in a number 
    .each(function(i,e){ 
    if (/\d$/.test(e.id)) { 
     // now that we only have ids that begin with storing and end in 
     // a number, bind the click event 
     $(e).click(function(e){ ... }); 
    } 
    }); 
+2

我不確定你想要通過映射來實現什麼......你最終會得到一個字符串數組,你不能綁定事件處理程序。 –

+0

@ FelixKling:確實,還在醒來。應該把邏輯放在點擊語句或每條語句中 –

+0

在這種情況下,我會使用'.filter'來代替;)不用擔心,早上好:) –

0

它可以是任何數量的東西。如果你向我們展示了更多的代碼,比如所有的aantalstoringen函數,這將有所幫助。

下面應該工作:

function aantalstoringen(storingen) { 
    $(document).ready(function() { 
     for (i=0;i<=storingen;i++) { 
      $("#storing" + i).click(function(){ centerPopup(); loadPopup(); }); 
     } 
    }); 
} 

也就是說,這是一個非常糟糕的方式做到這一點。我會讓你的每個元素也包括class="storing"。然後,您不必從服務器獲取對象的數量:

$(document).ready(function() { 
    $(".storing").click(function(){ centerPopup(); loadPopup(); }); 
}); 
+0

我向您展示了所有的aantalstoringen函數,它只是用於導入PHP跟蹤的變量。 – laarsk

0

首先給類的名稱,例如class =「popupDiv」。然後,你嘗試這樣

$('.popupDiv').live('click', function(){ 
     // var id = $(this).attr('id'); By doing so you will get the current id of the div too. 
     centerPopup(); 
     loadPopup(); 
}); 
0

布拉德正確地說,你不必知道這些元素的量,你可以遍歷有id開始與所有的東西元素。

所以,你的代碼是:

$(document).ready(function() { 
    $('[id^="storing"]').click(function() { 
     centerPopup(); 
     loadPopup(); 
    }); 
});