简体   繁体   中英

setting href value to javascript variable on click

I am trying to get the href value passed to a variable when the user clicks on the link from a particular class. This is what I have right now.

$(document).on('click',"a.show-notes",function{
    var $url = $(this).attr("href");
)};

This is not working for me though, and no value is being passed to the variable. I have also tried something like this, with no luck...

$("a.show-notes").on('click',function(){
    var $url = $(this).attr("href");
)};

I imagine that there is something obvious here that I am missing, but I've been starring at it for so long that my mind is fried.

Ensure you're setting those hooks after the DOM has loaded and those elements exist. Wrap them inside a $(document).ready function like this:

$(document).ready(function() {
  $("a.show-notes").on('click',function(){
    var url = $(this).attr("href");
    console.log(url);
  });
});

You have some syntax errors:

$(document).on('click',"a.show-notes",function(){
    var $url = $(this).attr("href");         //^missing parenthesis
    alert($url);
});
//^bad closing

Note: Also the $variable name convention is normally used only for jquery elements like:

var $element = $("li");

Try

$('a.show-notes').click(function(){
    var $url = $(this).attr('href');
});

The variable $url variable can be named however you like ( url , myLink , etc.) but it is only visible inside the click() function. If you want to use it outside, create the variable before the click() function, and set it inside.

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