【问题标题】:problem in loop for循环中的问题
【发布时间】:2011-06-24 01:54:44
【问题描述】:

我正在使用此代码,效果很好。现在我只需要更改输入的名称,输入 1,输入 2,等等。

<script type="text/javascript">
    $(document).ready(function() {
        $("#input1 > select.profissao").live('change', function(){ 
            $.ajax({
                type: "POST",
                data: "data=" + $(this).val(),
                url: "drop1.php",
                success: function(html) {
                    $("#input1 > select.estatistica").html(html);
                }
            });
        });
 });
</script>

为什么这个版本不起作用?我已经检查了 lint 中的代码,没有检测到错误。 基本上,如果我复制上面的代码并将 input1 更改为 input2,效果很好,但我的目标是减少冗余。

<script type="text/javascript">
    $(document).ready(function() {
        for (i=1; i<3; i++) {
        $("#input"+i+" > select.profissao").live('change', function(){ 
            $.ajax({
                type: "POST",
                data: "data=" + $(this).val(),
                url: "drop1.php",
                success: function(html) {
                    $("#input"+i+" > select.estatistica").html(html);
                }
            });
        });
        }
    });
</script>

编辑:输出类似于&lt;option value=2&gt;Artes&lt;/option&gt;&lt;option value=1&gt;Humanidades&lt;/option&gt;,但这并未添加到html中

使用循环我的下拉简单停止工作

【问题讨论】:

  • 你能把你的 HTML 贴出来吗,我感觉你可以在没有每个输入的事件处理程序的情况下处理这个问题。

标签: javascript loops for-loop


【解决方案1】:

你可以试试

<script type="text/javascript">
$(document).ready(function() {
    for (i=1; i<3; i++) {
        (function(idx){
            $("#input"+idx+" > select.profissao").live('change', function(){ 
            $.ajax({
                type: "POST",
                data: "data=" + $(this).val(),
                url: "drop1.php",
                success: function(html) {
                $("#input"+idx+" > select.estatistica").html(html);
               }
            });
            });
        })(i);
    }
});
</script>

并且您的函数在作用域中获得相同的 i 引用。

【讨论】:

  • 我认为这是正确的。这是因为 javascript 闭包。这里有一个很好的解释developer.mozilla.org/en/JavaScript/Guide/…
  • @user455318 如果您按类选择它们,jQuery 在内部将事件处理程序应用于所有元素。这比设置实时监控每个输入的更改事件更有效。
【解决方案2】:

顶部和底部块有不同的选择类是一个问题吗?

此外,串联方法似乎不太易于维护。

也许考虑使用类似的东西

  $('#input1, #input2, #input3').children('select.area').each(function () {
      $(this).live(...);
   });

编辑:在 ie 中换出选择的 html 内容也不是很受支持,并且给我带来了很多错误,所以您可能需要考虑每次都重新构建选择

【讨论】:

  • 选择的不同类别?在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2018-04-13
  • 2011-08-17
  • 2020-05-22
  • 2013-05-04
  • 2013-08-08
相关资源
最近更新 更多