开发者

Targeting dynamic text inside paragraph

开发者 https://www.devze.com 2023-03-21 00:15 出处:网络
I have some contact information, in which I wish to wrap the telephone number in a <a>, with the number in the href, for smartphone support.

I have some contact information, in which I wish to wrap the telephone number in a <a>, with the number in the href, for smartphone support.

The initial markup:

<p class="myClass">
    <a href="mailto:mail@mail.com">mail@mail.com</a><br />
    Phone: 88 88 88 88<br />
   开发者_如何学编程 Fax: 88 88 88 87<br />
</p>

Now, the markup will remain the same, however the numbers and addresses will change. Therefore, my first idea was to start an anchor after "Phone", and close it before the second break tag, then get that value and stick it in the href. Sadly, it doesn't work that way, as the tag is closed immediately.

$("p.myClass:contains('Phone')").each(function(){
    var org = "Phone: ";
    var rep = "Phone: <a>";

    $(this).html( $(this).html().replace(org, rep) );
    $("</a>").insertBefore("p.myClass:contains('Phone') br:nth-child(3)");
});

So what I really want to end up with, is to have the phone number wrapped, like so:

Phone: <a href="tel:{number}">{number}</a>

,where {number} is a dynamic value, and the rest of the markup remains the same. I'm looking for a solution that actually works, and which preferably cleaner than the mess I made above. :) Any ideas?


$("p.myClass:contains('Phone')").each(function(){
    var elem = jQuery(this);
    var html = elem.html().replace(/(Phone: )([^<]+)/i,"$1 <a href='tel:$2'>$2</a>");   
    elem.html(html); 
});

Running example


I would do this.

Wrap the telephone # in a span.

<p class="myClass">
    <a href="mailto:mail@mail.com">mail@mail.com</a><br />
    <span id="phone">Phone: 88 88 88 88</span><br />
    Fax: 88 88 88 87<br />
</p>

Then do the following

var phone = $('#phone').text().split(": ");
$('#phone').html(phone[0] + ': <a href="tel:' + phone[1] + '">' + phone[1] + '</a>');

http://jsfiddle.net/jasongennaro/ARUms/


Do you have control over the markup? If so, I'd suggest wrapping the various bits in <span class='xxx'> tags, where the class is phone/fax/email. That'll make it a lot easier to target the various bits for replacement. Or, go the whole hog and use the hCard microformat :-)

0

精彩评论

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