简体   繁体   English

从.attr('href')存储数字时,jQuery变量未定义

[英]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 http://jsbin.com/ukogam/2/edit

Is it because what jQuery is finding is html rather than the plain text of the number? 是否因为jQuery找到的是html而不是数字的纯文本? 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. 我知道$是未定义的,所以我包含了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); 然后我得到href不是函数,所以我修改了您提到的代码之后的一些代码: $("#main a").attr("href","/courses/" + courseID);

I think this is working how you expect? 我认为这对您的期望有效吗? http://jsbin.com/egevok/1/edit http://jsbin.com/egevok/1/edit

I modified it, have a look http://jsbin.com/iculoq/2/edit . 我修改了它,看看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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM