使用 javascript/jquery 在标题属性中插入换行符
问题:
我需要在工具提示中放置一个换行符,这样它就不会全部在一行上。我使用 tooltipsy 生成工具提示。它的工作原理是在任何锚标记上使用标题属性,并将“hastipy”类作为工具提示的内容。
因此,代码:
<a href="http://tooltipsy.com/" class="hastipy" title="Click here to go to the tooltipsy website">
tooltipsy
</a>
将是一个显示文本“tooltipsy”的链接,当您将鼠标悬停在其上时,它将在工具提示中显示“单击此处转到 tooltipsy 网站”。
但是,如果我想在工具提示内添加换行符怎么办?
此代码:
<a href="http://tooltipsy.com/" class="hastipy" title="Click here to <br /> go to the tooltipsy website">
tooltipsy
</a>
当您在 http://validator.w3.org 验证它时返回一堆错误
所以我来了up with this javascript/jQuery (由 Jason Gennaro 编写):
$('a').each(function(){
var a = $(this).attr('title');
var b = a.replace('lineBreak','\n');
$(this).attr('title', b);
});
此代码使用关键字(在本例中为 lineBreak)并将其替换为 \n
(<-- linebreak?) 所以我的代码通过了验证并且仍然有换行符在其中。
这段代码适用于 jsfiddle (这里是示例),但在我的网站上的工具提示内,事实并非如此。它插入了 \n
,但它并没有像预期的那样删除“lineBreak”。
任何人都可以对此提供解释,甚至可以解决它吗?
注意:
我不需要其他工具提示方法的建议,工具提示可以完美满足我需要的一切。
结果:
事实证明,仅使用
而不是
效果很好。
Question:
I need to put a linebreak inside my tooltip so it's not all on one line. I use tooltipsy to generate my tooltips. It works by using the title attribute on any anchor tags with the class "hastipy" as the content of the tooltip.
So the code:
<a href="http://tooltipsy.com/" class="hastipy" title="Click here to go to the tooltipsy website">
tooltipsy
</a>
Would be a link showing the text "tooltipsy" and when you hover over it, it would show "Click here to go to the tooltipsy website" in a tooltip.
However, what if I want to put a linebreak inside the tooltip?
This code:
<a href="http://tooltipsy.com/" class="hastipy" title="Click here to <br /> go to the tooltipsy website">
tooltipsy
</a>
returns a bunch of errors when you validate it at http://validator.w3.org
So I came up with this javascript/jQuery (written by Jason Gennaro):
$('a').each(function(){
var a = $(this).attr('title');
var b = a.replace('lineBreak','\n');
$(this).attr('title', b);
});
this code uses a keyword (lineBreak in this case) and replaces it with \n
(<-- linebreak?) so my code passes validation and still has the linebreak in it.
And this code works on jsfiddle (here is the example), but on my website inside the tooltip, it doesn't. It inserts the \n
, but it doesn't remove the "lineBreak" like it's supposed to.
Can anyone offer an explanation for this or even a possible fix for it?
Note:
I don't want a suggestion for another tooltip method, tooltipsy is working perfectly for everything I need.
Result:
As it turns out, just using <br />
instead of <br />
worked perfectly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用全局替换调用:
.replace(/lineBreak/g,'\n');
。如果要在标题属性中添加
,请使用:
(html 实体)。此外,JQuery 会自动将 JavaScript 包装在
$(document).ready(...)
内。你也应该这样做:Use a global replace call:
.replace(/lineBreak/g,'\n');
.If you want to add
<br />
in your title attribute, use:<br />
(html entities).Also, JQuery automatically wraps the JavaScript inside
$(document).ready(...)
. You should do the same: