Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过jquery访问以选择动态创建的控件_Javascript_Jquery_Json - Fatal编程技术网

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

Javascript 如何通过jquery访问以选择动态创建的控件,javascript,jquery,json,Javascript,Jquery,Json,我已经动态创建了一些select控件(也称为groupbox),但每次我尝试访问其中一个控件时,如果出现以下错误: Uncaught TypeError: undefined is not a function 代码如下: var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text(); 其中parseInt(buttonElementId+1始终是一个数字,因

我已经动态创建了一些select控件(也称为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>
返回真/假值,它不会继续jQuery链,因此没有要调用的
.text()
函数

正如在注释中指出的,要获取所选选项的文本,请执行以下操作:

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

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

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

每当没有选择任何选项时,您都无法捕获该选项,因为您直接引用了一个方法
.text()
为空。

请提供相关的html。在chrome中,如果单击控制台中的错误引用,也会将光标移到未定义的确切方法。这将有助于调试问题。正确的方法是:
=$(“#slt”+(parseInt(buttonElementId+1))。子项(“选项:选定”)。text()
,前提是HTML和脚本的所有其余部分都有效。@user3897247,
#sltWhateverNumber
是您的选择元素吗?如果不是,请更改选择器以选择选择元素