我正在编写一个函数,旨在将网页上文本字段的内容 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/