$(" .class")。val()返回未定义的值

时间:2017-03-15 03:11:29

标签: javascript jquery jquery-selectors getelementbyid

我已经连接到Trello API并使用Board中的列表创建了一个。然后,我尝试列出每个列表中的所有卡片。从value属性获取ListID时,它返回" undefined"。这是为什么?

我用document.getElementById("demo").innerHTML = $(".board").val();

打印出来
//HTML
<label>Choose from a List of Boards</label>
<div id="output"></div>

<label>Display Cards Below for Board Selected</label>
<div id="outputCards"></div>

<p id="demo"></p>

//Javascript
    var $boards = $("<select>")
            .attr("id", "boards")
        .text("Loading Boards...")
        .appendTo("#output");

    Trello.get("/boards/BOARD_ID/lists", function(boards) {
        $boards.empty();
        $.each(boards, function(ix, board) {
            $("<option>")
            .attr({href: board.url, target: "trello", value : board.id, name : board.id, id : board.id})
            .addClass("board")
            .text(board.name)
            .appendTo($boards);
        });  
    });


    var $cards = $("<div>")
        .text("Loading Cards...")
        .appendTo("#outputCards")
        .appendTo("#demo");

    // This is where I'm trying to return the value
    document.getElementById("demo").innerHTML = $(".board").val();

    var resource = "lists/LIST_ID/cards";
    Trello.get(resource, function(cards) {
        $cards.empty();
        $.each(cards, function(ix, card) {
            $("<a>")
            .attr({href: card.url, target: "trello"})
            .addClass("card")
            .text(card.name)
            .appendTo($cards);
        });  
    }); 

HTML输出如下:

<label>Choose from a List of Boards</label>
    <div id="output">
        <select id="boards">
            <option target="trello" value="LIST_ID" name="LIST_ID" id="LIST_ID" class="board">
                List One
            </option>
            ...
        </select>
    </div>

<label>Display Cards Below for Board Selected</label>
<div id="outputCards"></div>

<p id="demo">undefined</p>

1 个答案:

答案 0 :(得分:1)

我认为这里的主要问题是board类只被添加到Trello.get回调中的元素中。

由于此代码是异步执行的,因此在执行回调代码之前,您可能正在执行$(".board").val(),这意味着返回了`$(&#34; .board&#34;)没有元素。

我会考虑这样的事情

Trello.get("/boards/BOARD_ID/lists", function(boards) {
        $boards.empty();
        $.each(boards, function(ix, board) {
            $("<option>")
            .attr({href: board.url, target: "trello", value : board.id, name : board.id, id : board.id})
            .addClass("board")
            .text(board.name)
            .appendTo($boards);
        });  
        // This is where I'm trying to return the value

        $('#board').change(function () {
            document.getElementById("demo").innerHTML = $(".board:selected").val();
        });
    });