将文本附加到jQuery中的类中的匹配元素属性

时间:2009-04-30 18:19:46

标签: jquery regex

我正在尝试将查询参数附加到类中文本块内的链接,例如

<div class="container">
consectetur <a href="foo.php?q=bar">adipisicing</a>
</div>

其中附加了?q = bar。 这是我的功能:

function appendRef(container,reftag) {
    var Link = $(container).attr("href");
    var afterLink = reftag; 

        $(container).attr({
            href: (Link + afterLink)
            });
}


appendRef(".container a", "?q=bar");

但是,这会将div中的每个链接转换为它看到的第一个链接返回的值,而不是唯一地处理它们。我也希望能够根据原始网址的一部分过滤功能。像

这样的东西
if Link.match(/domain/) { //append the param 
}

4 个答案:

答案 0 :(得分:2)

正如您在函数开头设置Link变量时已经指出的那样,它将获取选择器返回的集合中第一个元素的值。在更新之前,您需要为集合中的每个元素计算href。

您可以通过调用.each并在闭包内使用.attr来执行此操作,或者您可以使用接受回调的attr版本并允许您逐个元素地执行逻辑... < / p>

$(".container a").attr("href",
    function(idx) { //idx is the index of the element in the set
        return this.href.match(/domain/) ? this.href + afterLink : this.href;
    }
 );

答案 1 :(得分:0)

是的,您正在将 Link 变量设置为静态值(第一个href之一)。

您必须将查询存储在如下变量中:

var links = $("." + container + " a");

所以 links 就是一个数组,然后你可以遍历它并将文本追加到它的href

答案 2 :(得分:0)

我自己不是jQuery人,但我知道css选择器会返回一系列结果。解决方案只是遍历元素并应用您想要的更改。此外,如果您想限制受影响的网址,我会在函数中添加一个可选的match属性来测试href

function appendRef(container,reftag, match) {
        match = match || /.*/
        $(container).each(function() {
           if ($(this).attr('href').match(match)) {
              //do url magic here
           }
        })
}

答案 3 :(得分:0)

太棒了,全都。 我建立了这个,并且还修改了它,所以如果原始链接已经有一个参数,它会将其剥离并替换为我们的新参数。

function appendRef(container, reftag, match) {
$(container).each(function() {

    if ($(this).attr('href').match(match)) {                
        var href = $(this).attr('href');                
        var href = href.replace(/\?.*$/,'');
        var href = (href + reftag);  
        $(this).attr('href', href);        

    }
});
}

appendRef(".container a", "?q=foo", "domain");