gpt4 book ai didi

jquery - 使用 Regex 和 JQuery 从页面获取链接号引用

转载 作者:行者123 更新时间:2023-12-01 03:35:52 26 4
gpt4 key购买 nike

如果:

var obj=[6849,6850]

我需要从页面上一系列链接的 href 属性中获取这两个数字。以下代码获取 6850,但不获取 6849

jQuery(document).ready(function() {
jQuery('a.title').each(function () {
var links=jQuery(this).attr('href');
if(links.indexOf('/')!=-1){
i=1;
}
else{
i=0;
}
var procura=links.match(/(\d+)/g)[i];
if(obj.indexOf(procura)!=-1){
....
}
};
});
});

如何将这两个号码传递给 procura

编辑:更新代码:

jQuery(document).ready(function() {
jQuery('a.title').each(function () {
var links=jQuery(this).attr('href');
if(links.indexOf('/')!=-1){
i=1;
}
else{
i=0;
}
var procura=links.match(/(\d+)/g)[i];

jQuery.each(obj,function(_,test) {
jQuery.each(procura,function(_,match) {
if(test.indexOf(match)!=-1){
...
}
});
});

});
});

最佳答案

我首先认为这是因为 .match 将返回找到的字符串数组,但您知道,因为如果有斜杠,您就将自己索引到第二个

document.write("1234sdfsf21312".match(/(\d+)/g))

所以我相信你正在寻找这个 - 我制作了 obj 字符串,否则它们没有 indexOf 这是一个字符串方法。

var obj=["6849","6850"];
$(function() {
$('a.title').each(function () {
var $link=$(this);
var href=$link.attr('href');
var idx = href.indexOf('/')!=-1?1:0; // choose the second one if slash
var procura=href.match(/(\d+)/g)[idx];
console.log(procura);
$.each(obj,function(_,test) {
if(test.indexOf(procura)!=-1) { // only works on strings
$link.attr("title",procura+" found");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="title" href="/6850/blabla/6849.jpg">Link 1</a>

获取最后的号码变化

    var idx = href.indexOf('/')!=-1?1:0; // choose the second one if slash
var procura=href.match(/(\d+)/g)[idx];

    var matches=href.match(/(\d+)/g);
var procura=matches.slice(-1).pop();

关于jquery - 使用 Regex 和 JQuery 从页面获取链接号引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com