带有select on change的jQuery array()

时间:2011-05-05 05:13:51

标签: php jquery

我试图通过将代码放入数组来最小化我的代码,但没有任何反应。我无法弄清楚我做错了什么。这是代码

<html>
    <head>

    <title>test</title>

    <!-- JavaScript -->
    <script src="js/jquery-1.5.2.js" type="text/javascript"></script>   
    <script type="text/javascript">

        var phpfile = new Object();
        phpfile["testselect"] = "zoomchange.php";


        var elementID = new Object();
        elementID["testselect"] = "#testdiv";

        $(document).ready(function(){

            $("select").change(function() {
              $.post(
                phpfile[$(this).id()],
                $(this).serialize(),
                function(data) {
                  $(elementID[$(this).id()]).html(data)
                }
              );

            });

        });

    </script>   

    </head>

    <body>


    <select id="testselect">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>

    <div id="testdiv"></div>

    </body>
</html>

这里是zoomchange.php:

<?PHP echo $_REQUEST['testselect'] ; ?>

3 个答案:

答案 0 :(得分:2)

您的初始化程序不应如下所示:

var phpfile = new Array();
phpfile["testselect"] = "zoomchange.php";

var elementID = new Array();
elementID["testselect"] = "#testdiv";

JavaScript数组由数字而非字符串索引。你想要简单的对象文字:

var phpfile   = { testselect: 'zoomchange.php' };
var elementED = { testselect: '#testdiv'       };

然后,你的POST回调很混乱:

function(data) {
    $(elementID[$(this).id()]).html(data)
}
调用该函数时,

this不是您认为的那样。你想要更像这样的东西:

$("select").change(function() {
    var that = this;
    $.post(
        phpfile[that.id],
        $(this).serialize(),
        function(data) {
            $(elementID[that.id]).html(data);
        }
    );
});

答案 1 :(得分:0)

您应该new Object()而不是new Array()编辑:还有其他错误,您的js代码应为:

<script type="text/javascript">
        var phpfile = {};
        phpfile["testselect"] = "zoomchange.php";

        var elementID = {};
        elementID["testselect"] = "#testdiv";

        $(document).ready(function(){

            $("select").change(function() {
              var $select = $(this);
              $.post(
                phpfile[$select.attr("id")],
                $select.serialize(),
                function(data) {
                  $(elementID[$select.attr("id")]).html(data)
                }
              );

            });
       });
</script>

答案 2 :(得分:0)

function(data)
{
  $(elementID[$(this).id()]).html(data);
}

而不是

function(data)
{
  $(elementID[$(this).id()]).html(data)
}

这是错误吗?

相关问题