简体   繁体   English

找到一个字符,然后使用jQuery在它之前插入HTML标记

[英]Find a character and then insert HTML tag before it with jQuery

I have some text that display using this markup that I can't change unfortunately 我有一些使用此标记显示的文本,很遗憾我无法更改

<a class="bt" href="#url">Leadership in Education (29 Oct - 31 Oct 2014)</a>

I'd like to append a <br /> just before the ( so that the date would display on a new line 我想在(之前添加一个<br /> ,以便日期显示在新行上

How do I go about of doing this? 我该怎么做?

Here's what I've been trying but with no idea how to execute what I'd like to achieve: 这是我一直在尝试的方法,但不知道如何执行我想要实现的目标:

http://jsfiddle.net/w6gp2af3/ http://jsfiddle.net/w6gp2af3/

$("a:contains('(')").html(function () {
    return $(this).html().replace(" (", "<br />("); 
});

jsFiddle example jsFiddle示例

jQuery selects DOM elements. jQuery选择DOM元素。 A bunch of text is not a DOM element, therefore you need to treat it like a string and use string.replace (or regex) to insert the BR where you want it. 一堆文本不是DOM元素,因此您需要将其视为字符串,然后使用string.replace(或regex)将BR插入所需的位置。

You can use jQuery to select the wrapping element. 您可以使用jQuery选择包装元素。 The rest is string manipulation. 其余的是字符串操作。

You don't want to do this for every a element on your page, so I suggest you add a selector to the code below where appropriate. 你不想为每个做a网页上的元素,所以我建议你在下面选择的代码添加在适当情况下。

The following code uses your selector, and replaces ( with <br>( . Very simple. 以下代码使用您的选择器,并将(替换为<br>( 。非常简单。

$( "a:contains('(')" ).each(function() {
    jQuery(this).html( jQuery(this).html().replace('(', '<br>(') );
});

You can use a regex to replace the open paren with a <br/>( . See fiddle: 您可以使用正则表达式用<br/>(代替打开的括号。参见小提琴:

http://jsfiddle.net/w6gp2af3/2/ http://jsfiddle.net/w6gp2af3/2/

Quick and Easy (this will work for all anchors on your page, so long as they only have one open parenthesis each...): 快速简便(此方法适用于页面上的所有锚点,只要每个锚点只有一个开放的括号即可...):

$( "a:contains('(')" ).css( "text-decoration", "underline" ).each(function(){
    $(this).html($(this).html().replace("(","<br/>("));
});

http://jsfiddle.net/hajx6ffz/ http://jsfiddle.net/hajx6ffz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM