使用jQuery,div中的相对路径会更新为绝对路径,但在将其重写为更动态时会遇到困难



下面的代码在特定的div中搜索所有具有指定URL的href。然后添加到域中以创建一个绝对路径。

$('#landing-page').find('a[href^="/catalog.php"]').each(function(element, index){
    var href = $(this).attr('href');
    href = href.replace('', 'http://www.mydomain.com');
    $(this).attr('href', href);
});
$('#landing-page').find('a[href^="/upgrade"]').each(function(element, index){
    var href = $(this).attr('href');
    href = href.replace('', 'http://www.mydomain.com');
    $(this).attr('href', href);
});

将鼠标悬停在这个小提琴中的链接上,可以看到它的动作。

我的下一步是让它更有活力,但我正在努力。我相信我需要创建一个数组,然后让它循环通过它。以下是我开始的。。。

var foo = {
    '/catalog.php',
    '/upgrade'
};
$('#landing-page').find('a[href^="' + foo + '"]').each(function(element, index){
    var href = $(this).attr('href');
    if (foo = href) {
        href = href.replace('', 'http://www.mydomain.com');
        $(this).attr('href', href);
    } 
});

这是小提琴。

我似乎无法让它发挥作用。其他时候,它会将域添加到所有链接中,这会产生新的问题。如有任何帮助,我们将不胜感激。感谢

首先,foo变量应该是数组,而不是对象。其次,您需要循环遍历该数组,并分别测试每个值。试试这个:

var foo = [
    '/catalog.php',
    '/upgrade'];
$.each(foo, function (i, value) {
    $('#landing-page').find('a[href^="' + value + '"]').attr('href', function(i, value) {
        return 'http://www.mydomain.com' + value;
    });
});

更新的小提琴

这似乎是一个相当奇怪的要求。你能不能直接更改来源?或者甚至使用base href元标签?

var foo = {
    '/catalog.php':'http://www.mydomain.com',
    '/upgrade':'http://www.mydomain2.com'
};
$.each(foo,function (search,prefix) {
    $('#landing-page').find('a[href^="' + search + '"]').each(function(element, index){
        $(this).attr('href',prefix + $(this).attr('href'));
    });
});

http://jsfiddle.net/U9RXL/1/

最新更新