简体   繁体   English

javascript show hide-处理文本内的html元素

[英]javascript show hide - handling html elements inside text

I am showing and hiding text with js - with buttons more and less 我在显示和隐藏文本与JS -带有按钮moreless

var showChar = 330;
var ellipsestext = '...';
var moretext  = "more";
var content = $('#content').html();            
if(content.length > showChar) {             
   var c = content.substr(0, showChar-1);
   var h = content.substr(showChar-1, content.length - showChar);             
   var html = c + '<span class="more">' + ellipsestext + '</span><span class="morecontent"><span>' + h + '</span><a href="" class="morelink">' + moretext + '</a></span>';             
   $('#content').html(html);
} 
$(".morelink").click(function(){
  if($(this).hasClass("less")) {
     $(this).removeClass("less");
     $(this).html(moretext);
  } else {
     $(this).addClass("less");
     $(this).html(lesstext);
  }
  $(this).parent().prev().toggle();
  $(this).prev().toggle();
  return false;
});

the problem i am having is: if the content can have sometimes 我的问题是:如果内容有时可以
<strong class="yellow">text</strong> and 330th char is somewhere in the middle of this strong element, it is cutting and the rest of the whole content is becoming yellow. <strong class="yellow">text</strong> ,第330个字符位于该强元素的中间位置,正在剪切,其余全部内容变为黄色。

how can I detect if more-less is going to cut html element and avoid this html destroying? 如何检测more-less是否要剪切html元素并避免此html破坏?

here is the fiddle: http://jsfiddle.net/Vvf8d/ 这是小提琴: http : //jsfiddle.net/Vvf8d/

您可以尝试使用$('#content').text()代替$('#content').html()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM