2011-10-16 27 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(); 
    }); 
});