strip span tags from string with jquery

眉间皱痕 提交于 2019-12-11 08:19:32

问题


I am wanting to take the text value of a p tag when I press enter

$.keynav.enterDown = function () {
  var accom = $('#suggestions p.keynavon').html();
  alert(accom);

}

This is working great but the results contain <span> and </span> tags, is there anyway I can strip those tags from the string?


回答1:


If you just want the text, which sounds like what you're after, use .text() instead of .html(), like this:

$.keynav.enterDown = function () {
  var accom = $('#suggestions p.keynavon').text();
  alert(accom);
}

If you actually need to strip the <span> tags specifically, clone the content (as to not affect the original) and replace them with their inner content via .replaceWith(), like this:

$.keynav.enterDown = function () {
  var accom = $('#suggestions p.keynavon').clone()
                .find('span').replaceWith(function() { return this.innerHTML; })
                .end().html();
  alert(accom);
}


来源:https://stackoverflow.com/questions/3797385/strip-span-tags-from-string-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!