从富文本字段内容创建列表项

时间:2016-01-05 03:50:52

标签: javascript jquery html css

我想从 div 输入标记中获取用户输入文字:

<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 = '';
  }
};

Here is the demo I'm working on

Here is the demo using a textarea tag

2 个答案:

答案 0 :(得分:1)

getElementsByClassName('editor')将返回类editor的元素数组,因此您不能只执行.value,您需要获取数组中的第一个元素。 / p>

另外,因为它是div,我想你想使用textContent,所以它看起来像这样

var inputText = document.getElementsByClassName('editor')[0].textContent

答案 1 :(得分:0)

  

对于您必须在javascript中编写的输入类型:

var input_val = getElementsByClassName('title').value;
  

你需要在你的javascript中写下div:

var div_val = getElementsByClass('editor').value;

我希望这会有效

相关问题