开发者

jQuery cut link

Here is html:

<a href="http://site.com/any/different/folders/picture_name.jpg">Go and win<开发者_Go百科;/a>
<a href="http://site.com/not/similar/links/some_other_name.png">Go and win</a>

How to cut all the data from a href, except picture_name.jpg? There can be any length of the link, we must take just the value from last / to last "

And anybody does know the shortest way to compare, if alt and title of current link are equal?

Thanks.


If you want to actually change the href to picture_name.jpg and some_other_name.png respectively, you can pass a function to .attr() and use .lastIndexOf()/.substring(), like this:

$("a").attr('href', function(i, href) {
  return href.substring(href.lastIndexOf('/') + 1);
});

You can view/play with a quick demo here


Alternatively if you're using a .each() you can get/use the value like this:

$("a").each(function() {
  var new_href = this.href.substring(this.href.lastIndexOf('/') + 1);
  //use it, e.g.: alert(new_href);
});​

You can see a demo of that here


var hrefs = $("a").map( function() {
  return this.href.substring(this.href.lastIndexOf('/')+1);
})

will return an array:

["picture_name.jpg", "some_other_name.png"]

Well, and the other question...

And anybody does know the shortest way to compare, if alt and title of current link are equal?

Sure, just compare them

var currentLink = $("a")[0]; // whatever

if (currentLink.alt == currentLink.title) {
  // some action
} else {
  // some other action
}


Once you grab the a element with getElementsByTagName or getElementById:

var parts = element.href.split('/')
last_part = parts[parts.length-1]


var a = $("#link");
var link = a.href;
alert( link.substr(0, link.lastIndexOf("/")+1) );
alert(a.href == a.title); 


You can also use a regular expression:

var url = element.href.match(/([^/]*)$/)[1];

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜