这就是我想要做的:单击按钮时,创建一个“p”元素,给它一个 id,将其 append 到父 div,然后获取输入字段的值并将其 append 到“innerHTML”新创建的“p”元素。请帮忙!
html:
<div id="main_container">
<h1 class="hero">TITLE</h1>
<div id="content_container">
<form id="form">
<label id="create_name">Create a username:</label>
<input id="input1"></input>
<button id="usr_btn">button</button>
</form>
</div>
</div>
js:
$('#usr_btn').on('click', function (e) {
if ($('#input1').val() != null) {
e.preventDefault();
var userName = document.createElement('p');
userName.id = 'name_created';
$('#name_created').append($('#content_container'));
$('#name_created').append($('#input1').val());
}
});
最佳答案
我建议:
//Declare the step variable
var step=0;
$('#usr_btn').on('click', function (e) {
if ($('#input1').val() != null) {
e.preventDefault();
//Increment ID's to make them unique
step++;
// using jQuery to create a <p> element, with
// an id of 'name_created', and using
// the 'text' property to set the textContent
// of the element:
var userName = $('<p>', {
'id' : 'name_created'+step,
'text' : $('#input1').val()
// appending the created element t '#content_container':
}).appendTo('#content_container');
}
});
您自己发布的代码中的一个问题是该行:
$('#name_created').append($('#content_container'));
将由“content_container”的 id
标识的元素 append 到创建的元素,而您的问题表明您要将创建的元素添加到#content_container
元素.
引用文献:
关于javascript - 如何获取输入值并将其 append 到新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436647/