将 br 插入文本节点
这可能看起来很奇怪。我有一个 id 为“quotes”的 div,里面有一个块引用。我认为如果引用的文本是诗歌,添加换行符会很有趣,并且我认为您可以使用“@”作为条件换行符,然后将其替换为 br 元素,如下所示:
function addBr() {
var c = document.getElementById("quotes");
var t = c.getElementsByTagName("blockquote");
var reg = new RegExp("@", "g");
for (var i = 0; i < t.length; i++) {
var r = t[i].lastChild.nodeValue.match(reg);
if (r !== null) {
var text = t[i].childNodes[0];
var q = t[i].lastChild.nodeValue.indexOf("@");
var x = document.createElement("br");
t[i].insertBefore(x, text.splitText(q));
t[i].lastChild.nodeValue = t[i].lastChild.nodeValue.replace(/\@/g, "");
}
}
}
这有效,但仅对于第一个例子,所以我需要一个循环,但我无法弄清楚。 div 会是这样的:
<div id = 'quotes'>
<blockquote> Some line, @ Some line, @ Some line@ </blockquote>
</div>
任何提示将不胜感激。
This might seem odd. I have a div with the id of 'quotes', and inside there is a blockquote. I thought it would be interesting to add line breaks, if the quoted text were poetry, and I thought you could use a '@' as a conditional line break, and then replace this with the br element as follows:
function addBr() {
var c = document.getElementById("quotes");
var t = c.getElementsByTagName("blockquote");
var reg = new RegExp("@", "g");
for (var i = 0; i < t.length; i++) {
var r = t[i].lastChild.nodeValue.match(reg);
if (r !== null) {
var text = t[i].childNodes[0];
var q = t[i].lastChild.nodeValue.indexOf("@");
var x = document.createElement("br");
t[i].insertBefore(x, text.splitText(q));
t[i].lastChild.nodeValue = t[i].lastChild.nodeValue.replace(/\@/g, "");
}
}
}
This works, but only for the first instance, so I need a loop, but I can't figure that out.
The div would be like this:
<div id = 'quotes'>
<blockquote> Some line, @ Some line, @ Some line@ </blockquote>
</div>
Any hints would be deeply appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从文本节点中最后一个匹配的
@
开始,然后向后进行。以下函数执行此操作,并且还具有消除不必要的正则表达式、使用更清晰的变量名称并且更短的优点:Start with the last match of
@
within the text node and work backwards. The following function does this and also has the benefit of eliminating the unnecessary regex, uses clearer variable names and is shorter:我建议简单地这样做:
什么是“条件换行符”?我在你的代码中没有看到任何决定何时断线的内容......
I would suggest simply doing this:
What is a "conditional line break"? I don't see anything in your code that decides when to break the line...