2013-02-12 207 views
2

不知道它是否实际上迭代一次,但只生成一个对话框。 jQuery的循环针对的是每个PHP循环迭代的隐藏输入,从1开始计数;总共有两个'roomID'。Jquery:循环迭代

使用警报给了我两个,但它没有分配与jquery对话,作为回报给我的第一个。这是为什么发生?

是否有这样做的更好的方法:

$('input#roomID').each(function() { 
    var roomID = $('input#roomID').val(); 
    alert($(this).val()); 

      $('div.edit-dialog-'+roomID).dialog({ 
       autoOpen: false, 
       height: 500, 
       width: 550, 
       modal: true, 
       position:['middle','middle'], 
       draggable: true, 
       //resizable: true, 
       buttons: { 
        Cancel: function() { 
         $(this).dialog("close"); 
        } 
       }, 
        close: function() { 
         allFields.val("").removeClass("ui-state-error"); 
        } 
      }); 

      $('a.room-edit-'+roomID).click(function() { 
       $('div.edit-dialog-'+roomID).dialog("open"); 
      }); 
    }); 

我有点新的jQuery的。

+0

对于此输入#roomID选择,您不能有多个dom元素。 – Elbek 2013-02-12 02:05:02

回答

5

你正在选择一个ID'#'。

Dom's需要唯一的id。

试着让它变成一个类。

所以不是

<input id="roomID" type="text" /> 

添加类

<input class="roomID" type="text" /> 

然后

$('input.roomID').each(); 

将与类roomID

选择页面上所有的输入编辑

jQuery的每个函数都会经过选择器匹配。所以说,你有这样的HTML:当你调用每个这样的

<input class="hello" /> 
<input class="hello" /> 
<span class="hello">text</span> 

然后:

$('.hello').each(function(i, ele){}); 

jQuery将调用该函数每次的功能都会有this(或将作用域)3次个人的dom元素。它按照它们在dom中出现的顺序执行此操作。所以第一次通过它将是input然后input然后span

每次this都会指向各自的dom元素而不是jQuery映射的元素。这就是为什么你需要做$(this)来访问jquery的辅助方法,而不仅仅是this.val()

它也调用带有2个参数的函数,第一个是迭代数,所以在span的情况下,这将是2.第二个是元素。

+0

试过,dennmat。同样的结果。 – Joe 2013-02-12 02:06:31

+0

你还需要更新你的行'var roomID = $('input#roomID').val();''到'$(this).val()'。 – dennmat 2013-02-12 02:07:38

+0

OOO!那样做了!这也非常有意义。由于我是jquery的新手,但理解PHP的循环...我的假设是通过使用特定的'input#roomID',它抓住了第一个,而不是每个迭代都会改变的$(this)? <3 – Joe 2013-02-12 02:12:24

0

如果您使用another selecto r来定制输入,这会好得多。

<input name="new3" /> 
<input name="new2" /> 
<input name="new1" /> 

<script> 
    $('input[name*="new"]').val('xxxxx'); 
</script>