2017-03-16 63 views
1

我需要這一個尋求一些幫助所以這裏去...JQuery的檢測空p標籤

我創建使用CONTENTEDITABLE textarea的WYSIWYG編輯器。它會自動創建段落,並且還可以添加字幕。

我想做什麼就能做的是按鈕#addStorySubtitle被點擊時,如果當前選定的p標籤爲空或只包含一個零寬度空間​,那麼它將被innerDivSubtitle的內容所取代。但是,如果p標籤包含內容,請使用innerDivSubtitle在下面創建新的塊級元素。

我似乎有麻煩的部分是檢測是p標籤是空的。

謝謝大家!

$('#addStorySubtitle').click(function(e){ 
    var innerDivSubtitle = $('<div class="addStorySubtitleWrap" contenteditable="false"><span class="removeStorySubtitle"></span><textarea name="addstorysubtitle" class="addStorySubtitle autoSize" placeholder="Really good subtitle" contenteditable="true"></textarea></div><p>&#8203;<p>'); 

    var sel = window.getSelection(); 
    if ($(sel.anchorNode.parentNode) === "") { 
    alert('empty'); //just for help 
    $(sel.anchorNode.parentNode).replaceWith(innerDivSubtitle); 
    } else { 
    alert('not empty'); //just for help 
    $(sel.anchorNode.parentNode).after(innerDivSubtitle); 
    } 
}); 

UPDATE

感謝您的所有有用的答覆!

事實證明,零寬度空間檢測導致了問題,我不得不使用unicode來檢測它。這裏就是我所做的修復它...

var nodCon = $(sel.anchorNode.parentNode).html(); 
    if (nodCon === "" || nodCon === "\u200b"){ 
    alert('empty'); 
    } 
+0

'alert'不是調試器。 –

+0

http://stackoverflow.com/questions/6813227/how-do-i-check-if-an-html-element-is-empty-using-jquery –

+0

'p'標籤不應該是空的。 – Teemu

回答

0

我希望這會幫助你?

if($('p').html() == "" || $('p').html == "&#8203;"){ 
    //Do something 
} 
0

檢查空的方式如下:

if ($("Your p tag").val().length == 0) { /* Empty */ } 
+0

對不起格式化,我在手機上。 – Maxime2400

0

您可以檢查元素是否有這樣的內容:

checkElementContents(document.getElementById('p1')); 
 
checkElementContents(document.getElementById('p2')); 
 

 
function checkElementContents(element) { 
 
    if (element.innerHTML) { 
 
    console.log(element.id + " is not empty"); 
 
    } else { 
 
    console.log(element.id + " is empty"); 
 
    } 
 
};
<p id="p1"></p> 
 
<p id="p2"> </p>

0

小心空間,回車等...

function isEmpty(ele) 
{ 
    var count = ele.html().replace(/\s*/, ''); 
    if(count>0) 
     return false; 
    return true; 
} 

console.log(isEmpty($('p')));