0

我正在尝试执行以下一点点 jQuery:

    var c = 1;
$("#bench-box .pid-switch").each(function(){
    $(this).attr('name', 'pidsarray['+c+']');
    c = c + 1;
});

如果我将它输入到萤火虫控制台并以这种方式运行,它会完美运行。这告诉我选择器正在寻找我想要它找到的东西,并且它正在按照我想要的方式执行。

但是,如果我在代码中将其作为函数调用,而不是通过控制台调用,则它不起作用。它不会导致错误,它只是不会执行。我一个接一个调用的函数列表中的其余代码继续正常工作。

我无法弄清楚为什么它通过控制台工作而不是其他方式。这是我在代码中的调用方式:

$("#button").click(function() {
    adjustPids();
});

function adjustPids() {
var c = 1;
$("#bench-box .pid-switch").each(function(){
    $(this).attr('name', 'pidsarray['+c+']');
    c = c + 1;
});    
}

有什么想法吗?

编辑:

上面的 jQuery 代码按照正常情况包装在 $(document).ready(function () 中。我在原来的问题中没有提到这一点很糟糕。

4

3 回答 3

0

据我所知,您发布的代码没有任何问题,控制台中是否有错误?如果您打算调试而不是我建议将 Firefox 与 Firebug 或 Chrome 一起使用(不需要插件);按 f12 打开开发人员工具并在控制台中查看输出:

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
    $(document).ready(function(){
        $("#button").click(function() {
            console.log("ok, clicked");
            adjustPids();
        });

        function adjustPids() {
            var c = 1;
            console.log("adjustPids");
            $("#bench-box .pid-switch").each(function(){
               console.log("and this is",this);
               $(this).attr('name', 'pidsarray['+c+']');
                c = c + 1;
            });         
        };
    });
</script>
</head>
<body >
<div id="bench-box">
    <div class="pid-switch">hello</div>
    <div class="pid-switch">hello</div>
    <div class="pid-switch">hello</div>
</div>
<input type="button" id="button" value="click me" />
</body>
</html>
于 2013-02-08T03:40:33.710 回答
0

我很抱歉。现在一切正常。我只是重写了它并移动了一些东西。(虽然我重写了完全相同的代码,但我找不到从以前到现在的任何差异......非常令人困惑)。

所以我不确定它为什么起作用,但我很高兴它起作用了,我将继续我的下一个任务。

感谢您的所有帮助,无论如何。

于 2013-02-08T03:43:04.633 回答
-1
    var c = 1;
$("#bench-box .pid-switch").each(function(i,elm){
    $(elm).attr('name', 'pidsarray['+c+']');
    c = c + 1;
});
于 2013-02-08T03:39:31.267 回答