如以下代码片段所示,我有多个文本 div,其中有一个粗体部分,然后是一个换行符,然后是一段文本。我可以 find() 粗体部分,但是如何使用 javascript/jquery 仅获取粗体部分后换行符后面的文本部分?
<div class="thecontent">
any amount of text or html elements before
<b>
the bolded text
</b>
<br>
the text I need together with the bolded text which can contain other html
elements apart from line breaks and bolded blocks
<br>
<b>
posibility of more bolded and text couples further in the div
</b>
<br>
and some more text to go with the bolded text
</div>
单个 div 中可以有多个粗体部分和文本对,所需的文本片段可以以换行符、另一个粗体部分或 div 的结尾结束。可能还有其他 html 元素,如 <a href>
在文本 block 中。
我可以得到 <b> </b>
的内容与 .find('b')
我试过使用 nodeType == 3
选择文本节点,但这只会让我获得所有文本。
很遗憾,我无法更改页面的 html。有人有解决办法吗?提前致谢:)
根据要求,输入将以粗体显示,以阻止换行符及其后的文本。我需要在换行符或另一个粗体部分之前的文本。
输出将是一个变量中的粗体文本和换行符之后但直到下一个换行符或另一个变量中的粗体元素的文本。
所以 html 示例的输出是:the bolded text
+ the text I need together with the bolded text which can contain other html
elements apart from line breaks and bolded blocks
和posibility of more bolded and text couples further in the div
+ and some more text to go with the bolded text
最佳答案
我不认为有一种非常简单的方法来获取所有节点并将它们分开等,但它肯定是可能的。由于我不知道你打算用文本做什么,我制作了一个简洁的小对象,其中包含应该更容易使用的所有内容,或者你可以更改代码以满足你的需要:
var elem = $('.thecontent').get(0).childNodes,
content = {},
i = 0;
for (key in elem) {
var type = elem[key].tagName ? elem[key].tagName : 'text';
content[i] = {};
content[i][type] = elem[key].tagName == 'B' ? $(elem[key]).text() : elem[key].nodeValue;
i++;
}
console.log( content );
返回:
{"0": {"text" : "any amount of text or html elements before"},
"1": {"B" : "the bolded text"},
"2": {"text" : "\n"}, //also returns newlines
"3": {"BR" : null},
"4": {"text" : "the text I need together with the bolded text which can contain other html elements apart from line breaks and bolded blocks"},
"5": {"BR" : null},
"6": {"text" : "\n"},
"7": {"B" : " posibility of more bolded and text couples further in the div"},
"8": {"text" : "\n"},
"9": {"BR" : null},
"10":{"text" : "and some more text to go with the bolded text"},
}
您可以根据行号(从零开始)、标记名、文本内容或您需要的任何其他内容进行过滤?
关于javascript - 使用 javascript/jquery 选择仅跟随某些元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14894691/