我想从这个 div 和 input 标签中获取用户输入的文本:
<input id="title" placeholder="Title (Optional)">
<div class="editor" contenteditable></div>
div 是一个富文本字段,我用它代替了常规的 textarea 标签
并在 <ul>
中创建一个列表项标签。
这是我得到的 javascript,但无法正常工作...
(在常规文本区域中工作得很好,但在富文本格式中我什么也得不到)
/*------POST SUBMIT JS------*/
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementsByClassName('editor').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
最佳答案
getElementsByClassName('editor')
将返回具有类 editor
的元素数组,因此您不能只执行 .value
,需要获取数组的第一个元素。
另外,因为它是一个 div,我想你想使用 textContent
,所以它看起来像这样
var inputText = document.getElementsByClassName('editor')[0].textContent
关于javascript - 从富文本字段内容创建列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34603865/