开发者

How to style parentheses and the text inbetween them?

I have a line of text:

<h1 class="productName">Product Name (Blue)<开发者_Go百科;/h1>

and I wish to style the parentheses and the text inbetween - ideally placing a span around them.

I have tried adapting the solution here, but I can't get it to work.


If you have this HTML:

<div id="test">Product name (colour)</div>

You can use this javscript to add the span as requested:

var o = document.getElementById("test")
o.innerHTML = o.innerHTML.replace(/\([^\)]*\)/, '<span class="highlight">$&</span>');

And, then set CSS for the class to control the formatting.

If you want to replace more than one, then you would have to add the g flag and change the regex slightly for min match instead of max match to this:

var o = document.getElementById("test")
o.innerHTML = o.innerHTML.replace(/\([^\)]*?\)/g, '<span class="highlight">$&</span>');.

You can see it work here: http://jsfiddle.net/jfriend00/NyaZ2/.

OK, now that you've included the HTML, you can do it using jQuery like this:

var o = $(".productName");
o.html(o.html().replace(/\([^\)]*?\)/g, '<span class="highlight">$&</span>'));


<!-- load jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('h1').each(function(){
        var splitChar = '(';
        var tmp = $(this).text().split(splitChar);
        if (tmp.length == 2) {
            $(this).html(tmp[0] + '<span>(' + tmp[1] + '</span>');
        }
    });
});
</script>
<style> span { color: #c00; } </style>
<body>
        <h1>Product name (colour)</h1>
        <h1>Product name (colour)</h1>
        <h1>Product name (colour)</h1>
        <h1>Product name (colour)</h1>
        <h1>Product name (colour)</h1>
        <h1>Product name (colour)</h1>
</body>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜