2017-09-02 51 views
3

總覽:我有一個可編輯的div部分。下面的股利,還有它創建了一個span元素的按鈕,插入在span元素文本「標籤」,最後追加span元素在編輯DIV爲什麼文本會附加到錯誤的html元素?

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
    <style type="text/css"> 
     #sample-div 
     { 
      border-style: solid; 
      border-width: 1px; 
      border-color: black; 
      height:100px; 
      overflow: auto; 
     } 
    </style> 
    <script type="text/javascript"> 
     function addTags() 
     { 
      var tag = document.createElement("span"); 
      tag.className = "tag" 
      tag.innerHTML = "tag"; 
      $('#sample-div').append(tag); 
     } 
    </script> 
</head> 
<body> 
<div id="sample-div" contenteditable="true"></div> 
<input type="button" value="date" id="sample-tags" onclick="addTags()"> 
</body> 
</html> 

觀察:我按一下按鈕,跨度元素被添加到預期

<div id="sample-div" contenteditable="true"> 
    <span class="tag">tag</span> 
</div> 
<input type="button" value="date" id="sample-tags" onclick="addTags()"> 

不過,我開始DIV中鍵入後格,我注意到以下幾點:

<div id="sample-div" contenteditable="true"> 
    <span class="tag">tag this is a continuation</span> 
</div> 

期望是:

<div id="sample-div" contenteditable="true"> 
    <span class="tag">tag</span> this is a continuation 
</div> 

所以,我的問題是,爲什麼文本「這是一個延續」也越來越附加span元素裏面?我如何達到我預期的目標?

+0

我認爲contenteditable div內的所有文本都需要在某種子標籤內。 –

+0

@GetOffMyLawn,不正確:https://jsfiddle.net/mdeenbvv/1/ –

+0

「這是一個延續」的文本從哪裏來的? –

回答

3

最簡單的解決辦法是設置你的跨度contentEditable屬性是false

function addTags() { 
    var tag = document.createElement("span"); 
    tag.className = "tag" 
    tag.innerHTML = "tag"; 
    tag.contentEditable = false; 
    $('#sample-div').append(tag); 
} 

邊注:由於您使用jQuery,你不需要手動創建標籤:

function addTags() { 
    var tag = '<span class="tag" contenteditable="false">tag</span>' 
    $('#sample-div').append(tag); 
} 
相關問題