gpt4 book ai didi

Javascript (JQuery) 删除最后一个单词

转载 作者:行者123 更新时间:2023-11-28 08:25:41 27 4
gpt4 key购买 nike

我需要从溢出元素中删除最后一个单词,直到该元素的内容不再溢出。我已经尝试过了

var pageHeight = 25.7; //This is cm, but I can convert to px easily enough
var pageContent = "";
var d = $("<div />").appendTo('body');
function removeLast(d){
//remove last word
var str = $(d).html()
var lastIndex = str.lastIndexOf(" ");
var str = str.substring(0, lastIndex);
$(d).html(str);
if ($(d).height() > pageHeight){
removeLast(d); //to try and loop around
}
}

还有这个

$(d).html( trimSentence($(d).html()) );
if ($(d).height() > pageHeight){
removeLast(d);
}

(以下来自另一个答案,似乎工作正常)

function trimSentence(string){
var found = false;
var index = null;

var characterGroups = string.split(' ').reverse();

var position = 1,//skip the first one since we know that's the end anyway
elements = characterGroups.length,
element = null,
prevHadUpper = false,
last = null,
lookFor = '';

while(!found && position < elements) {
element = characterGroups[position].split('');

if(element.length > 0) {
last = element[element.length-1];

// test last character rule
if(
last=='.' || // ends in '.'
last=='!' || // ends in '!'
last=='?' || // ends in '?'
(last=='"' && prevHadUpper) // ends in '"' and previous started [A-Z]
) {
found = true;
index = position-1;
lookFor = last+' '+characterGroups[position-1];
} else {
if(element[0] == element[0].toUpperCase()) {
prevHadUpper = true;
} else {
prevHadUpper = false;
}
}
} else {
prevHadUpper = false;
}
position++;
}


var trimPosition = string.lastIndexOf(lookFor)+1;
return string.substr(0,trimPosition);
}

但是当使用循环时,两者似乎都不起作用,但在没有循环的情况下却可以正常工作。我试图减少 div 内容的长度,直到没有溢出,并且“溢出”文本应该复制到另一个字符串中(但这可能是另一个问题)

最佳答案

使用text()方法代替html():

var str = $(d).text()

html() 包含 html 标记,但 text() 方法仅包含文本字符串。

关于Javascript (JQuery) 删除最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22450922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com