简体   繁体   中英

jQuery variable undefined when storing number from .attr('href')

I'm trying to get the number from this link

   <div id="section-tabs-header">
   <a id="section-tabs-header-subtitle" class="ellipsis" href="/courses/123456">Math 101</a>

and store it in a variable

var courseID = $("div#section-tabs-header a#section-tabs-header-subtitle").attr("href").match(/\d+/);
console.log(courseID);

but the variable is "undefined."

http://jsbin.com/ukogam/2/edit

Is it because what jQuery is finding is html rather than the plain text of the number? How do I get just the number?

I didn't see anything about the variable being undefined. I got that $ was undefined so I included jQuery. Then I got that href wasn't a function so I modified some code that was after the code you mentioned to this: $("#main a").attr("href","/courses/" + courseID);

I think this is working how you expect? http://jsbin.com/egevok/1/edit

I modified it, have a look http://jsbin.com/iculoq/2/edit .

var courseID = $("#section-tabs-header-subtitle").attr("href").split('/')[2];

$("#main a").attr('href', "/courses/" + courseID);
var href = $("#section-tabs-header-subtitle")
  .attr("href");
console.log(href);
var courseID =  href.match(/\d+/);
console.log(courseID);

$("#main a").attr("href","/courses/" + courseID); 

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