简体   繁体   中英

$(this).attr(“href”) not working

For some reason, this line of code is returning undefined for $(this).attr("href")

$("a").attr("href", "javascript:page('" + $(this).attr("href") + "')");

How can I get that value?

$("a").click(function(e){
    e.preventDefault();
    page(this.href);
});

Try:

$("a").attr("href", function (index, oldHref) {
    return "javascript:page('" + oldHref + "')");
});

Check out the documentation for attr for information about the overload that takes a function reference.

Although as @Pointy points, out, you should consider writing an event handler instead of using javascript: inside your markup.

This is an alternative approach that doesn't require Javascript on your href attribute

$('a').click( function(e) {
    e.preventDefault();
    page(this.href);
} )

You don't need inline javascript, why not do like below:

$("a").click(function(){
    page(this.href);
    return false;
});

If you want to do that (update all href attribute of the links on the page) you could do

$("a").each(function() {
   $(this).attr("href", "javascript:page('" + $(this).attr("href") + "')");
});

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