如何通过jquery访问以选择动态创建的控件

时间:2014-09-11 16:13:13

标签: javascript jquery json

我已经动态创建了一些选择控件(a.k.a.groupbox),但每次我尝试访问其中一个控件时如果出现以下错误:

Uncaught TypeError:  undefined is not a function

以下是代码:

var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();

parseInt(buttonElementId + 1总是一个数字,所以错误不存在

<html>
<head lang="en">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
    <style>
        body        { padding-top:80px; }
        html, body, #wrapper
        {
            width: 100%;
            height: 100%;
        }
    </style>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div class="container">
        <div id="information"></div>
        <div id="tableInformation"></div>

        <div id="goBack"></div>
        <br/>
        <div id="inputDiv"></div>
        <br/>
        <br/>
        <div id="UserGuide"></div>
    </div>

    <script src="js/jquery-1.11.js"> </script>
<script>
    var apiUrl = 'http://localhost/devices';
    $( document ).ready(function() {
        // Handler for .ready() called.
        jsonGETRequest(apiUrl, jsonExampleData);

    });
    $(document).on('click', ':button' , function() {
        // reference clicked button via: $(this)

        $("#UserGuide").empty();
        var buttonElementId = $(this).attr('id');
        if(buttonElementId.indexOf("btnShowFunc") > -1) {
            buttonElementId = buttonElementId.replace("btnShowFunc","");
            deviceUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) + 1)].cells[1].innerHTML;
            goBack = "firstAPIRequest";
            $("#tableInformation tbody").remove();
            jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
        } else if(buttonElementId.indexOf("btnGoBack") > -1 ) {
            switch (goBack) {
                case "firstAPIRequest":
                    goBack = "";
                    $("#tableInformation tbody").remove();
                    jsonGETRequest(apiUrl, jsonExampleData);
                    removeGoBackInputDiv();
                    break;
                case "secondAPIRequest":
                    goBack = "firstAPIRequest";

                    $("#tableInformation tbody").remove();
                    jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
                    removeGoBackInputDiv();
                    break;
            }
        }else if(buttonElementId.indexOf("btnRunFunc") > -1) {
            goBack = "secondAPIRequest";
            buttonElementId = buttonElementId.replace("btnRunFunc","");
            var functionUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) +1)].cells[2].innerHTML;

            var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
            $("#tableInformation tbody").remove();
            $("#inputDiv").empty();
            // /jsonPOST(apiUrl  '/functions/' + functionUID )
        }

    });

    function loadDataIntoDeviceGrid(jsonData) {
        //$("#tableInformation").addClass("table table-responsive table-bordered");
        var tbl=$("<table/>").attr("id","mytable");
        $("#tableInformation").append(tbl);
        $("#mytable").append("<tr>" + "<th>dal.device.status</th>" + "<th>dal.device.UID</th>"
                + "<th>dal.device.driver</th>"  + "<th>service.id</th>" +"<th></th>" + "</tr>");
        for(var i=0;i<jsonData.length;i++)
        {
            var tr  = "<tr>";
            var td1 = "<td>"+jsonData[i]["dal.device.status"]+"</td>";
            var td2 = "<td>"+jsonData[i]["dal.device.UID"]+"</td>";
            var td3 = "<td>"+jsonData[i]["dal.device.driver"]+"</td>";
            var td4 = "<td>"+jsonData[i]["service.id"]+"</td>";

            //@Deprecated var dataList = fillSelectControl(jsonData[i]["objectClass"]); @Deprecated
            var btn = "<td>" +  "<button id='btnShowFunc"+ i + "' class='btn btn-success btn-lg'>See function</button>" + "</td></tr>";

            $("#mytable").append(tr + td1 + td2 + td3 + td4 + btn );

        }
        $("#mytable").addClass("table table-responsive table-bordered");
    }
    function loadInformationDeviceGrid() {
        $("#UserGuide").addClass("alert alert-info");
        $("#UserGuide").html("<h3>Getting devices list:</h3><br/> "+
                "Using this request, you can retrieve a list of all the available devices."+
                "For every device, among other info, there is the indication of the device unique ID, which" +
                "can be used to directly access to the device and the indication of the device driver (ZigBee, Bluetooth, etc.).<br/>If you want see some request response example please visit this <a href='#'>site</a>");
    }

    function removeGoBackInputDiv() {
        $("#inputDiv").empty();
        $("#btnGoBack").remove();
    }

    function loadDataIntoFunctionsGrid(jsonData) {
        $("#mytable").append("<tr>" + "<th>function.device.UID</th>"
                + "<th>service.id</th>"  + "<th>function.UID</th>"  + "<th>operation.names</th>" + "<th></th>" + "</tr>");
        var tr, td2, td3, td4, dt2, btn;
        for(var i = 0; i < jsonData.length; i++) {
             tr = "<tr>";
             //@Deprecated td1 = "<td>" + jsonData[i]["CLASS"] + "</td>";
             td2 = "<td>" + jsonData[i]["al.function.device.UID"] + "</td>";
             td3 = "<td>" + jsonData[i]["service.id"] + "</td>";
             td4 = "<td>" + jsonData[i]["dal.function.UID"] + "</td>";
             //@Deprecated dt1 = fillSelectControl(jsonData[i]["objectClass"]);
             dt2 = fillSelectControl(jsonData[i]["dal.function.operation.names"], i);
             btn = "<td>" +  "<button id='btnRunFunc"+ i + "' class='btn btn-success btn-lg'>Run</button>" + "</td></tr>";
            $("#mytable").append(tr + td2 + td3 + td4  + dt2 + btn );
        }
        createGoBackButton();
        createInputTextParameters();
    }

    function loadInformationFunctionsGrid() {
        $("#UserGuide").addClass("alert alert-info");
        $("#UserGuide").html("<h3>Getting device functions:</h3><br/>"
                              + "This API is used to retrieve the list of the available functions supported by the device. For"
                              + "example a Smart Plug has two functions: one to retrieve the energy consumption and another"
                              + "'boolean' function useful to change the status of the smart plug (ON/OFF). Every function"
                              + "indicates the id, which can be used to access directly the function and the list of the operation"
                              + "that can be invoked on the function.<br/>"
                              + "P.S. If he want use a function that want some parameters he must write these into the dedicated textbox. If the API needs more parameters separate these using comma. <br/>"
                              + "Example of parametes: <br/> <code>'type':'java.math.BigDecimal'</code><br/> <code>'value':1</code> <br/> etc...");
    }
    function createGoBackButton() {
        var btn = '<button id="btnGoBack"  class="btn btn-warning btn-lg">Go Back</button>';
        $("#goBack").append(btn);
    }

    function createInputTextParameters() {
        var lbl ="<label>Paramters</label>";
        var txt ='<input type="text" class="form-control" name="email">';
        $("#inputDiv").addClass("form-group");
        $("#inputDiv").append(lbl);
        $("#inputDiv").append(txt);

    }

    function fillSelectControl(obj, id) {
        var dataList = "<td><select id='slt"+ id +"'>";
        for(var j = 0; j < obj.length; j++)
            dataList = dataList + "<option value='" + obj[j] + "'>" + obj[j] + "</option>";
        return dataList = dataList + "</select></td>";
    }
    var json = "";
    var goBack = "";
    var deviceUID;
    function jsonGETRequest(url, dataExample){
        $.getJSON(apiUrl, function(data) {
            alert(JSON.stringify(data));
            this.json = data;
        })
                .done(function() {
                    $("#information").addClass("alert alert-success");
                    $("#information").text("getJSON request succeeded!");
                    if(goBack == "") {
                        loadDataIntoDeviceGrid(jsonExampleData);
                        loadInformationDeviceGrid();
                    } else if (goBack=="firstAPIRequest") {
                        loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
                        loadInformationDeviceGrid();
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    //alert('getJSON request failed! ' + textStatus);
                    $("#information").addClass("alert alert-danger");
                    $("#information").text("Impossible get data from API, it will be use example data" + errorThrown);
                    if(goBack == "") {
                        loadDataIntoDeviceGrid(jsonExampleData);
                        loadInformationDeviceGrid();
                    } else if (goBack=="firstAPIRequest") {
                        loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
                        loadInformationFunctionsGrid();
                    } else if(goBack=="secondAPIRequest") {

                    }
                })
                .always(function() {  });
    }
    function jsonPOST(url, method, paramters, dataExample) {

    }
    var jsonExampleData = [
        {
            "dal.device.status": 2,
            "dal.device.UID": "ZigBee:test123",
            "dal.device.driver": "ZigBee",
            "service.id": 28,
            "objectClass": [
                "org.osgi.service.dal.Device"
            ]
        },
        {
            "dal.device.status": 2,
            "dal.device.UID": "ZigBee:test456",
            "dal.device.driver": "ZigBee",
            "service.id": 29,
            "objectClass": [
                "org.osgi.service.dal.Device"
            ]
        },
        {
            "dal.device.status": 2,
            "dal.device.UID": "ZigBee:test789",
            "dal.device.driver": "ZigBee",
            "service.id": 30,
            "objectClass": [
                "org.osgi.service.dal.Device"
            ]
        }

    ];
    var jsonExampleDataFunctions = [
        {
            "CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
            "dal.function.device.UID": "ZigBee:test123",
            "service.id": 27,
            "dal.function.UID": "ZigBee:test123:testButton",
            "objectClass": [
                "org.osgi.service.dal.Function"
            ],
            "dal.function.operation.names": [
                "getData",
                "reverse",
                "setFalse",
                "setTrue"
            ]
        },
        {
            "CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
            "dal.function.device.UID": "ZigBee:test456",
            "service.id": 26,
            "dal.function.UID": "ZigBee:test456:testButton",
            "objectClass": [
                "org.osgi.service.dal.Function"
            ],
            "dal.function.operation.names": [
                "getData",
                "reverse",
                "setFalse",
                "setTrue"
            ]
        },
        {
            "CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
            "dal.function.device.UID": "ZigBee:test789",
            "service.id": 25,
            "dal.function.UID": "ZigBee:test789:testButton",
            "objectClass": [
                "org.osgi.service.dal.Function"
            ],
            "dal.function.operation.names": [
                "getData",
                "reverse",
                "setFalse",
                "setTrue"
            ]
        }
    ];
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

.is()返回一个true / false值,它不会继续jQuery链,因此没有.text()函数可以调用

正如DevishOne在评论中指出的那样,获取所选选项的文本:

=$("#slt" + (parseInt(buttonElementId + 1))).children("option:selected").text();

答案 1 :(得分:0)

将其拆分为多个步骤并检查特定结果:

 button = $("#slt" + (parseInt(buttonElementId + 1)));
 if ( button )
 {
     childs = button.children("option");
     if ( childs .....

如果没有选择任何选项,则无法捕捉到该选项,因为您直接引用方法.text()为null。