无法阅读财产'匹配'未定义的

时间:2015-01-28 13:01:32

标签: javascript jquery

我正在运行以下内容:

var token = document.location.href.split('?s=')[1].match(/[a-z0-9]+/);
var longString = "?s=" + token + "?_sft_category=";
var tokenB = document.location.href.split(longString)[1].match(/[a-z0-9]+/);
var attribuB = "." + tokenB;
jQuery('a[data-filter-value="' + attribuB + '"]').parent().parent().parent().find(".dropdown-toggle").html(tokenB).append(' <span class="caret"></span>');

我怎么来的?

Uncaught TypeError: Cannot read property 'match' of undefined

如果我删除.match(/[a-z0-9]+/)我没有收到任何错误,但我确实需要match ..

网址如下:

http://www.example.com/xchanges/results/?s=sky&_sft_category=ogilvy

3 个答案:

答案 0 :(得分:3)

可能在这里使用库会更好。我开发了一个与网址一起使用的小型JavaScript库:url.js

<script src="path/to/url.js"></script>
<script src="your-js.js"></script>

然后你可以这样做:

var token = Url.queryString("s");
var tokenB = Url.queryString("_sft_category");

就是这样。

请注意,您可以使用parent()方法,而不是多次调用closest()

$('a[data-filter-value="' + attribuB + '"]')
   .closest("<your_container>")
   .find(".dropdown-toggle")
   .html(tokenB)
   .append(' <span class="caret"></span>')
   ;

答案 1 :(得分:2)

您的location.href可能不包含您的longString。如果您使用href中不存在的字符串拆分href,那么您只剩下一个只有1个字符串的数组,因此您无法获得[1]元素。 这一切都取决于你的token变量是什么....

您使用过&#39;?&#39;字符两次,这是不正确的。 我使用

var tokenB = document.location.href.split('_sft_category=')[1].match(/[a-z0-9]+/);

获取所需的值,因为_sft_category=可能只在location.href中出现一次,然后您应该能够将href拆分为2的数组。 为您节省2行代码;)...

答案 2 :(得分:0)

您在?中使用了longString两次,这反过来会使split()返回一个只有一个值的数组。您需要将其更改为:

var longString = "?s=" + token + "&_sft_category=";

?字符只能在查询字符串的开头使用一次。

相关问题