javascript中最大字符的链接不起作用

时间:2013-11-20 18:22:50

标签: javascript html

我已经运行了一个js来查看是否达到了最大字符数。它有文本和href,但是当达到最大字符数时,链接不起作用并将其转换为文本。当限制小于580个字符时,链接起作用。当它达到限制时,读取更多链接确实有效。任何建议或帮助请,谢谢

$(document).ready(function () {
var stylistText = $('#stylistText');
var stylistText2 = document.getElementById("stylistText").innerHTML;
var countActualText = stylistText2.valueOf().length;
var maxLength = 580;
var aElement = document.createElement('a');
var linkText = document.createTextNode(" ...Read more");
aElement.appendChild(linkText);
aElement.href = "#";

if (countActualText > maxLength) {
    stylistText.text(stylistText.text().substring(0, 580));       
    stylistText.append(aElement);
   }
});

这是html

    <div class="stylistInfo">        
        <img id="stylistPhoto" src="images/Test.jpg" alt="peekaboo beans stylist" />
        <p id="stylistText">
            <a href="sdf">This is supposed to be a link</a> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.
        </p>
    </div>

1 个答案:

答案 0 :(得分:0)

更改stylistText.text(stylistText.text().substring(0, 580));stylistText.html(stylistText.html().substring(0, 580));

但是,截断包含HTML的文本块可能会导致其他问题,尤其是在截断发生在元素中间的情况下。我建议重新考虑你的整个战略。