简体   繁体   中英

Split value of a html tag

I would like to split some content from an "a" html tag. I was starting over with jquery. My code is like this but it is not working:

$("a.uribb").each(function() {
    var id = $(this).attr("href").replace("http://dereferer.org/?", "");
    $(this).append(+id+);
});

​ And the HTML tag is this:

<a href="http://dereferer.org/?http://example.com/" target="_blank" class="uribb">
    http://example.com/
</a>

I wanted to split out the http://dereferer.org/? part and leave the other there. How could I do this?

Try to use .text() instead of .append() if you want to replace the content. Also, there is no need for the + before and after the id.

You could try this instead:

var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).text(id);

Update

Reading through the question again, I'm not sure if you want to replace the content of the a -tag or the the value of the href. In case of the latter, try this:

var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).attr("href", id);

Notice

Since jQuery 1.6, it is preferred to use .prop() instead of .attr() .

How about that?

$("a.uribb").attr("href", function(i, val) {
    return val.substring(val.indexOf("?") + 1);
});​

DEMO: http://jsfiddle.net/zQdL4/


It's interesting but for your markup the following code should also work :)

$("a.uribb").attr("href", function() {
    return $.trim(this.innerHTML);
});​

Right, so what you want is this.

<a href="http://example.com/">...

Try this.

$("a.uribb").each(function() {
    var indirect_url = $(this).prop("href");
    var direct_url = indirect_url.replace("http://dereferer.org/?", "")
    $(this).prop('href', direct_url);
});

You could of course do this in fewer lines, but this way it's clear what's going on. Specifically, replace() does not modify the string it operates on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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