JQuery检测空p标签

时间:2017-03-16 12:34:49

标签: javascript jquery html

我需要请求一些帮助,所以这里......

我正在使用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);
  }
});

更新

感谢所有有用的回复!

事实证明,零宽度空间检测导致了问题,我不得不使用unicode来检测它。这就是我为解决它而采取的措施......

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

4 个答案:

答案 0 :(得分:0)

我希望这会对你有帮助吗?

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

答案 1 :(得分:0)

检查是否以下列方式清空:

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

答案 2 :(得分:0)

您可以检查元素是否包含以下内容:

&#13;
&#13;
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");
  }
};
&#13;
<p id="p1"></p>
<p id="p2"> </p>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

小心空格,回车等......

231