How i do apply attr to all href's on my page. For example: I have :
<ul>
<li><a href="mylink1">mytext1</a></li>
<li><a href="mylink2">mytext2</a></li>
<li><a href="mylink3">mytext3</a></li>
</ul>
I need:
<ul>
<li><a href="javascript:myFunc(mylink1)">mytext1</a></li>
<li><a href="javascript:myFunc(mylink2)">mytext2</a></li>
<li><a href="javascript:myFunc(mylink3)">mytext3</a></li>
</ul>
I need do this without adding new id's, classes and etc. Use Js and jQuery. Please, help! :)
Something like this should work:
$("ul li a").each(function(i, a) {
a = $(a);
a.attr('href', 'javascript:myFunc("' + a.attr('href') + '")');
});
Note: this will apply this to only links within ul
lists. To apply to all a
tags across the entire page, use $("a")...
instead.
Also, this method may fail if the href
attributes contain certain characters like "
or \\
. If this is a possibility, then this is a bit safer:
$("ul li a").each(function(i, a) {
a = $(a);
a.attr('href', 'javascript:myFunc(' + JSON.stringify(a.attr('href')) + ')');
});
You can try like
$('a').each(function () {
var att = $(this).attr('href');
$(this).attr("href", "javascript:myFunc(" + att + ")");
});
Using jQuery:
$("a[href^='mylink']").on('click', function(e) {
e.preventDefault();
myFunc($(this).attr("href"));
});
this shoud do what you need:
$("a").each( function() {
var url = $(this).attr('href');
$(this).attr('href', 'javascript:myFunc("'+url+'")');
});
Instead of modifying the href
assign the event handler in the actual Javascript:
$("[href]").click(function(e){
e.preventDefault();
myFunc(this.href);
});
function myFunc(value){
alert(value);
}
JS Fiddle: http://jsfiddle.net/Rs9RH/
Try This:
$('li a').each(function(){
$(this).attr('href',"javascript:myFunc("+$(this).attr('href')+")");
})
I think this could works:
$("a[href^='mylink']").each(function () {
var url = $(this).attr('href');
$(this).attr("href", 'javascript:myFunc("'+url+'")')
})
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.