javascript - JQuery 函数仅打印出未定义

标签 javascript jquery html list append

我正在编写一个函数,旨在将网页上文本字段的内容 append 到列表中,以便 HTML 的另一部分可以在文本字段上方呈现列表内容。字段和按钮出现并且响应良好,但打印出来的唯一内容是“未定义”而不是文本字段的内容。这是 JavaScript 函数:

<sp:script>


$('#append').on('click', function () {
   var text = $('#new-text').val();
   var li = '<li>' + text + '</li>';
   $('#target-list').append(li);
});

</sp:script> 

这是渲染文本、文本字段和按钮的代码:

    <!-- adding text -->
        <div class="tab-content"> <!-- begin div -->
                <div class="clearfix">
                    <div class="form-group col-sm-4">

                    <ul id ="target-list"> <!-- begin rendering existing text -->
                        <g:each var="newText" in="${instance.newTexts}">
                            <li class ="list-item">
                                ${newText} 
                            <input type="hidden" name="newText" value=${newText}"/>
                            </li>
                        </g:each>
                    </ul> <!-- end rendering existing text -->
                    <!-- enter text field start -->
                        <input class="form-control required" type="text" id="new-email" placeholder="Enter additional email addresses"/>


                        <!-- enter text field end -->
                    </div>
                    <br>
                    <!-- begin code for add button -->  
                    <button type="button" class="btn btn-sm btn-green" title="Add mew text"
                        id = "append">

                        <i class="fa fa-plus"></i>
                    </button> <!--  end button div -->
                </div>
                               
            </div>

我有什么遗漏吗?

最佳答案

您的输入没有 ID“#new-text”。这将导致 $('#new-text').val() 未定义。尝试添加 ID。

<input id="new-text" type="hidden" name="newText" value=${newText}"/>

关于javascript - JQuery 函数仅打印出未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32874430/

相关文章:

jquery-mobile-960 流体布局在 <li> 内使用时散布网格 block

jQuery Roundabout IE 图像像素化

javascript - 无法在 Firefox 中的 Window 上监听 DOMMouseScroll

javascript - Node.js 中的套接字异常

jquery - 如何在 jQuery Galleria 插件中自动切换 showinfo?

jquery - 在灯箱暂停按钮后重新加载多个 iframe 并导致所有 iframe 仅显示一个视频

php - 使用php将数据插入mysql

javascript - 循环中的 jQuery 单击事件被 float 属性破坏

javascript - Ember 数据 RestAdapter 嵌入了 hasMany

javascript - jQuery 监听所有文本输入变化