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

标签 javascript jquery json

我动态创建了一些选择控件(也称为组框),但每次我尝试访问其中一个控件时,如果出现以下错误:

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>

最佳答案

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

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

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

关于javascript - 如何通过jquery访问选择动态创建的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25792344/

相关文章:

javascript - "new"如何与 javascript 中的类一起使用?

javascript - 显示/隐藏 div 以使用 jquery 进行过滤

Jquery 在新窗口中打开链接

php - 自动更新 ext.data.store 上的新数据

json - osticket api 获取门票

javascript - 使用 AngularJs,当子集合中的数据被过滤掉时,如何隐藏元素?

javascript - 通过创建实例来修改的类变量

javascript - 将图像放在一起并在窗口加载时为图像设置动画

java - 将 JSON 映射到 POJO 时出现 UnrecognizedPropertyException

javascript - 工厂中的 AngularJS $http 请求